leecode更新
This commit is contained in:
parent
c5ccd201f4
commit
dbbfcf9e45
|
|
@ -89,6 +89,68 @@ public class ThreeSum {
|
|||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
return parentList;
|
||||
|
||||
}
|
||||
|
||||
//更简洁一点的思路
|
||||
public static List<List<Integer>> threeSum1(int[] nums) {
|
||||
|
||||
List<List<Integer>> parentList = new ArrayList<>();
|
||||
|
||||
if (nums.length < 3) {
|
||||
return parentList;
|
||||
}
|
||||
//先排序
|
||||
Arrays.sort(nums);
|
||||
|
||||
//后累加
|
||||
//第一个数的索引i
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
|
||||
if(nums[i]>0) break;
|
||||
|
||||
//为了避免这一次和前一次重复
|
||||
if (i > 0 && nums[i] == nums[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
//第三个数的索引k
|
||||
int k = nums.length - 1;
|
||||
|
||||
//第二个数的索引
|
||||
int j=i+1;
|
||||
|
||||
|
||||
|
||||
//开始遍历
|
||||
while(j<k){
|
||||
//三数之和
|
||||
int sum = nums[i]+nums[j]+nums[k];
|
||||
if(sum<0){
|
||||
//不够了
|
||||
j++;
|
||||
|
||||
}else if(sum>0){
|
||||
//太多了
|
||||
k--;
|
||||
|
||||
}else {
|
||||
parentList.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[j],nums[k])));
|
||||
//为了避免和上一次重复
|
||||
while (j<k&&nums[j+1]==nums[j]){j++;} //相同中间数只能出现一次
|
||||
while (j<k&&nums[k-1]==nums[k]){k--;} //相同最大数只能出现一次
|
||||
j++;
|
||||
k--;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue