首页 > 代码库 > LeetCode 3Sum
LeetCode 3Sum
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)
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] num) { 3 HashSet<List<Integer>> set = new HashSet<List<Integer>>(); 4 int len=num.length; 5 Arrays.sort(num); 6 for (int i = 0; i < len-2; i++) { 7 if (num[i]>0)break; 8 for (int j = len-1 ; j >i+1 ; j--) { 9 if (num[j]<0) break;10 int ab = num[i] + num[j];11 int c = -ab;12 int k = bs(c, num, i + 1, j - 1);13 if (k>0) {14 ArrayList<Integer> list = new ArrayList<Integer>();15 list.add(num[i]);16 list.add(num[k]);17 list.add(num[j]);18 set.add(list);19 }20 }21 }22 return new ArrayList<List<Integer>>(set);23 }24 int bs(int c, int[] num, int l, int r) {25 if(num[l] > c || num[r] < c) return -1;26 while(l <= r) {27 int m = (l+r)/2;28 if(num[m] == c) return m;29 else if(num[m] < c) l = m+1;30 else r = m-1;31 }32 return -1;33 }34 }
LeetCode 3Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。