leetcode 三数之和
题目: 给你一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
解题思路: 先将数组进行排序, 然后遍历数组, 因为要求a + b + c = 0 所以必有一个数 < 0, 因此遍历数组找到所有 < 0的数作为a, 再用双指针法找到其余两个数
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>>ans = new ArrayList<List<Integer>>();
if(nums.length < 3 || nums == null) return ans;
Arrays.sort(nums);
if(nums[0] > 0) return ans;
for(int i = 0;i < nums.length && nums[i] <= 0;i++){
if(i != 0 && nums[i - 1] == nums[i]) continue; // 防止重复元素
int target = 0 - nums[i];
int j = i + 1,k = nums.length - 1;
while(j < k){ //
int sum = nums[j] + nums[k];
if(sum == target){
ans.add(Arrays.asList(nums[i],nums[j],nums[k]));
while(j < k && nums[j] == nums[j + 1]) j++;
while(j < k && nums[k] == nums[k - 1]) k--;
j++;
k--;
}
else if(sum < target) j++;
else k--;
}
}
return ans;
}
}