问题描述:
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
这道题用到了List,鉴于很久没接触Java了,这道题没有自己独立完成,其实想了想,要是我自己写的话,应该是这么个思路:三重循环,计算三个数的和是否为target,但看了别人的高效代码后,觉得这样直接写应该会产生重复的结果。
先上代码吧:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums); //先给数组排序,方便后续程序的进行
for (int i = 0; i + 2 < nums.length; i++) {
if(i>0 && nums[i]==nums[i-1]) continue; //防止重复的结果
int j = i+1;
int k = nums.length-1;
int target = -nums[i];
while(j<k){
if(nums[j]+nums[k] == target){
res.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++;
k--;
while(j<k && nums[j]==nums[j-1]) j++; //防止重复的结果
while(j<k && nums[k]==nums[k+1]) k--; //防止重复的结果
}else if(nums[j]+nums[k] > target){
k--;
}
else{
j++;
}
}
}
return res;
}
}
涉及到的Java知识:
Arrays.asList() 是将数组作为列表