马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。public class Solution2 {
public List<List<Integer>> threeSum(int[] nums) {
//官方答案******************************************
Arrays.sort(nums);
int len = nums.length;
List<List<Integer>> arrayList = new ArrayList<>();
for (int first = 0; first < len; first++) {
if (first > 0 && nums[first]==nums[first-1]){
//跳出本次循环
continue;
}
int third = len-1;
int target = -nums[first];
for (int second = first+1; second < len; second++) {
if (second > first+1 && nums[second]==nums[second-1]){
//跳出本次循环
continue;
}
while (third > second && nums[second]+nums[third] > target){
third--;
}
if (second == third){
break;
}
if(nums[second]+nums[third]==target) {
List<Integer> l = new ArrayList<>();
l.add(nums[first]);
l.add(nums[second]);
l.add(nums[third]);
arrayList.add(l);
}
}
}
return arrayList;
}
}
遍历第三个数的时候,条件是 while (third > second && nums[second]+nums[third] > target){
third--;
}
,为什么不可以是nums[second]+nums[third] != target |