LeetCode 3sum 问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 3sum 问题相关的知识,希望对你有一定的参考价值。
1、
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)
2、
这道题引申与2sum问题,之后还可以继续引申4sum。
具体的思路就是双指针的灵活应用;
3、我的解法:
1 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 2 public List<List<Integer>> threeSum(int[] num) { 3 4 if (num == null || num.length < 3) return ret; 5 6 Arrays.sort(num); 7 8 int len = num.length; 9 for (int i = 0; i < len-2; i++) { 10 if (i > 0 && num[i] == num[i-1]) continue; 11 find(num, i+1, len-1, num[i]); //寻找两个数与num[i]的和为0 12 } 13 14 return ret; 15 } 16 public void find(int[] num, int begin, int end, int target) { 17 int l = begin, r = end; 18 while (l < r) { 19 if (num[l] + num[r] + target == 0) { 20 List<Integer> ans = new ArrayList<Integer>(); 21 ans.add(target); 22 ans.add(num[l]); 23 ans.add(num[r]); 24 ret.add(ans); //放入结果集中 25 while (l < r && num[l] == num[l+1]) l++; 26 while (l < r && num[r] == num[r-1]) r--; 27 l++; 28 r--; 29 } else if (num[l] + num[r] + target < 0) { 30 l++; 31 } else { 32 r--; 33 } 34 } 35 }
以上是关于LeetCode 3sum 问题的主要内容,如果未能解决你的问题,请参考以下文章