File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
src/main/java/com/geekidentity/leetcode/n0015 Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .geekidentity .leetcode .n0015 ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .Arrays ;
5
+ import java .util .List ;
6
+
7
+ /**
8
+ * 15. 三数之和
9
+ * https://leetcode-cn.com/problems/3sum/
10
+ * 1. 暴击
11
+ * 2. 双指针,左右下标向中间推进
12
+ */
13
+ public class ThreeSum {
14
+ public List <List <Integer >> threeSum1 (int [] nums ) {
15
+ List <List <Integer >> result = new ArrayList <>();
16
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
17
+ for (int j = i + 1 ; j < nums .length - 1 ; j ++) {
18
+ for (int k = j + 1 ; k < nums .length ; k ++) {
19
+ if (nums [i ] + nums [j ] + nums [k ] == 0 ) {
20
+ result .add (Arrays .asList (nums [i ], nums [j ], nums [k ]));
21
+ }
22
+ }
23
+ }
24
+ }
25
+ return result ;
26
+ }
27
+
28
+ public List <List <Integer >> threeSum2 (int [] nums ) {
29
+ List <List <Integer >> result = new ArrayList <>();
30
+ Arrays .sort (nums );
31
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
32
+ if (i > 0 && nums [i ] == nums [i - 1 ]) continue ;
33
+ for (int j = i + 1 , k = nums .length - 1 ; j < k ;) {
34
+ int target = -nums [i ];
35
+ int sum = nums [j ] + nums [k ];
36
+ if (sum == target ) {
37
+ result .add (Arrays .asList (nums [i ], nums [j ], nums [k ]));
38
+ j ++;
39
+ k --;
40
+ while (j < k && nums [j ] == nums [j - 1 ]) {
41
+ j ++;
42
+ }
43
+ while (j < k && nums [k ] == nums [k + 1 ]) {
44
+ k --;
45
+ }
46
+ } else if (sum < target ) {
47
+ j ++;
48
+ } else {
49
+ k --;
50
+ }
51
+ }
52
+ }
53
+ return result ;
54
+ }
55
+ }
You can’t perform that action at this time.
0 commit comments