File tree 1 file changed +8
-0
lines changed
src/com/blankj/medium/_015
1 file changed +8
-0
lines changed Original file line number Diff line number Diff line change 10
10
* blog : http://blankj.com
11
11
* time : 2017/10/14
12
12
* desc :
13
+ * 题意是让你从数组中找出所有三个和为 0 的元素构成的非重复序列,这样的话我们可以把数组先做下排序,
14
+ * 然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 0 的大小来移动两个指针,
15
+ * 其中细节操作就是优化和去重。
13
16
* </pre>
14
17
*/
15
18
public class Solution {
16
19
public List <List <Integer >> threeSum (int [] nums ) {
17
20
List <List <Integer >> list = new ArrayList <>();
18
21
int len = nums .length ;
19
22
if (len < 3 ) return list ;
23
+ // 先排序
20
24
Arrays .sort (nums );
21
25
int max = nums [len - 1 ];
26
+ // 最大值小于0, 那么不存在sum == 0 的解
22
27
if (max < 0 ) return list ;
23
28
for (int i = 0 ; i < len - 2 ; ) {
29
+ // 最小值小于0, 那么不存在sum == 0 的解
24
30
if (nums [i ] > 0 ) break ;
25
31
if (nums [i ] + 2 * max < 0 ) {
26
32
while (nums [i ] == nums [++i ] && i < len - 2 ) ;
27
33
continue ;
28
34
}
35
+ // 对于任意一个nums[i],在数组中的其他数中解2sum问题,目标为target-sums[i]
29
36
int left = i + 1 , right = len - 1 ;
30
37
while (left < right ) {
31
38
int sum = nums [i ] + nums [left ] + nums [right ];
32
39
if (sum == 0 ) {
33
40
list .add (Arrays .asList (nums [i ], nums [left ], nums [right ]));
41
+ // 去重
34
42
while (nums [left ] == nums [++left ] && left < right ) ;
35
43
while (nums [right ] == nums [--right ] && left < right ) ;
36
44
} else if (sum < 0 ) ++left ;
You can’t perform that action at this time.
0 commit comments