【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;
}
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;
}
相关文章推荐
- 个人记录-LeetCode 15. 3Sum
- leetCode 15. 3Sum (3数之和) 解题思路和方法
- leetcode解题报告15. 3Sum
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- [LeetCode]3Sum,解题报告
- LeetCode 15. 3Sum 三个正数之和
- Leetcode 15. 3sum
- [leetcode]15. 3Sum
- [leetcode] 【数组】15. 3Sum
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- Leetcode 15. 3Sum
- LeetCode解题记录(5)
- LeetCode-15. 3Sum
- LeetCode 15. 3Sum(三数之和)
- Leetcode习题记录——3Sum Closest
- leetcode_15. 3Sum-求数组中三个数和为0
- leetcode 15. 3Sum
- leetcode小白解题记录——第一题
- [LeetCode-Java]15. 3Sum
- leetcode小白解题记录——第十题