您的位置:首页 > 其它

【Leetcode解题记录】15. 3Sum

2018-02-12 23:24 369 查看
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]
]
-----
先对数组进行排序,固定一个标点,设置两个指针,左指针和右指针,分别从标点之后的位置和数组的最后一个位置开始计算。
排序的好处就是可以避免数值重复。public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
for (int i =0;i<nums.length-2;i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
left = i +1;
right = nums.length - 1;
while (left < right) {
if(nums[i]+nums[left]+nums[right]==0){
list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
lists.add(list);
while(left<right&&nums[left]==nums[left+1]) left++; //如果遇到下一个数值相等就往右移动
while(left<right&&nums[right]==nums[right-1]) right--; //如果遇到下一个数值相等就往左移动
left++;
right--;
}else if(nums[i]+nums[left]+nums[right]<0){
left++;
}else{
right--;
}
}
}
return lists;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: