【LeetCode】#15三数之和(3Sum)
题目描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
Description
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法
class Solution{
public List<List<Integer>> threeSum(int[] nums){
Arrays.sort(nums);
int iNum = Integer.MAX_VALUE;
int jNum;
int kNum;
List<List<Integer>> res = new ArrayList<>();
for(int i=0; i<nums.length && nums[i]<0; i++){
if(iNum==nums[i]){
continue;
}
iNum = nums[i];
int j = i + 1;
int k = nums.length-1;
while(j<k){
int sum = nums[i] + nums[j] + nums[k];
if(sum>0){
k--;
}else if(sum<0){
j++;
}else{
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
res.add(list);
jNum = nums[j];
do{
j++;
if(j>=k){
break;
}
}while(jNum==nums[j]);
kNum = nums[k];
do{
k--;
if(j>=k){
break;
}
}while(kNum==nums[k]);
}
}
}
return res;
}
}