您的位置:首页 > 其它

leetcode(15)3sum

2017-10-05 16:25 344 查看
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]

]

因为本人比较菜,所以一开始想的当然是N3的遍历,但是一个medium的题目肯定不能这么简单,所以这题就理解为成a+b = -c的题目。然后可以用双指针做,遍历num[],0-num[i]作为-c,left指针从i+1开始向右遍历,right从右开始向左遍历。

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//先排序
Arrays.sort(nums);
//避免重复,将获得的list先放入set中
Set<List> sets = new HashSet<>();
for(int i=0;i<nums.length;i++){
//如果num[i]>0就出现不了=0的情况所以break
if (nums[i]>0)break;
int target = 0-nums[i];
int j = i+1;int k = nums.length-1;//定义左右指针
while (j<k){
if (nums[j]+nums[k] == target){
List<Integer> set = new ArrayList<>();
set.add(nums[i]);set.add(nums[j]);set.add(nums[k]);
sets.add(set);
j++;k--;
}
//如果左右指针的数的sum小于target则从用更大的比较,所以j++,同理,如果小于target,则k--;
else if (nums[j]+nums[k]<target){
j++;
}
else {
k--;
}
}
}
List<List<Integer>> lists = new ArrayList<>();
for (List list: sets){
lists.add(list);
}
return lists;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: