3Sum
来源:互联网 发布:双十一大学生网购数据 编辑:程序博客网 时间:2024/04/29 16:28
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>> result = new ArrayList<>(); if(nums == null || nums.length == 0) return new ArrayList<>(); Arrays.sort(nums); for(int i=0;i<nums.length;i++){ if( i != 0 && nums[i] == nums[i-1]) continue; int low = i+1; int high = nums.length-1; while(low<nums.length && low<high){ int sum = nums[low] + nums[high]; //System.out.println(sum); if(sum == -nums[i]){ List<Integer> ret = new ArrayList<>(); ret.add(nums[i]); ret.add(nums[low]); ret.add(nums[high]); result.add(ret); high--; low++; while(low < high && nums[low] == nums[low-1]){ low++; } while(low < high && nums[high] == nums[high+1]){ high--; } } if(sum > -nums[i]){ high--; } if(sum < -nums[i]){ low++; } } } return result; }
0 0
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- 3Sum
- 3Sum
- 3Sum
- Leetcode Sum Root to Leaf Numbers
- JavaScript之HTML DOM
- Leetcode Linked List Cycle II
- javascript dom simpledemo
- 说说UIViewController那些事儿(下)
- 3Sum
- Leetcode Reorder List
- Leetcode Binary Tree Postorder Traversal
- Git 远程操作
- FaceBook面试题 Implement strStrp(String a, String b)
- Leetcode Kth Smallest Element in a BST
- [Leetcode] 34. Search for a Range 解题报告
- Spring基础:快速入门spring cloud(3):业务逻辑服务
- 【LeetCode】 018. 4Sum