【Leetcode】3Sum (Sum)
来源:互联网 发布:詹姆斯07总决赛数据 编辑:程序博客网 时间:2024/04/26 03:43
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)这道题首先对num数组排序,然后求0~i-1里面加和等于-num[i]的数
因为它要求找唯一的组合,所以需要避免重复
代码来自Code_Ganker
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();if (num == null || num.length <= 2)return result;Arrays.sort(num);for (int i = num.length - 1; i >= 2; i--) {if (i < num.length - 1 && num[i] == num[i + 1])continue;ArrayList<ArrayList<Integer>> twoRes = twoSum(num, i - 1, -num[i]);for (int j = 0; j < twoRes.size(); j++)twoRes.get(j).add(num[i]);result.addAll(twoRes);}return result;}public ArrayList<ArrayList<Integer>> twoSum(int[] num, int end, int target) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();int left = 0;int right = end;while (left < right) {if (num[left] + num[right] == target) {ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(num[left]);temp.add(num[right]);result.add(temp);left++;right--;while (left < right && num[left] == num[left - 1])left++;while (left < right && num[right] == num[right + 1])right--;} else if (num[left] + num[right] > target)right--;elseleft++;}return result;}
0 0
- 【Leetcode】3Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- 2014秋C++第11周项目4参考-特殊三位数
- Homebrew
- 初步了解dojo js框架之学习实例
- Hadoop工程包架构解析
- HTML5对最终用户的3大优势
- 【Leetcode】3Sum (Sum)
- Linux学习视频地址
- 2014秋C++第11周项目5参考-当年第几天
- 深度解析Android中字体设置
- Android用户界面之常用控件ListView 属性大全
- 《数学之美》摘要
- eclipse中文版变成英文版
- 星星评分
- HTML5已定稿:将彻底颠覆原生应用