15. 3Sum

来源:互联网 发布:极限音波拉皮 知乎 编辑:程序博客网 时间:2024/06/08 04:55

转载自 http://algorithm.books.mafengshe.com/answer/3.html

15. 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: 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]]

题目翻译

一个包含n个整数的数组S,判断S中是否存在元素a + b + c = 0,查找数组中所有和为零的三元组。

注意:解决方案集不能包含重复的三元组。

例如,数组S = [-1,0,1,2,-1,-4]答案是:[  [-1 , 0 , 1],  [-1 , -1 , 2]]

解题方案

标签: Array

思路:
- 首先对数组进行排序,时间复杂度为O(n*logn)
- 然后对数组进行两层的遍历,先取出当前遍历的数字为nums[i],然后从数组两侧取出数字分别为nums[begin]和nums[end],然后三个数求和值为sum
- sum == 0,将三个数加入结果之中,同时将两侧的下标向中间移动,直到不与之前取出的数字相同,避免出现重复的三元组
- sum > 0,因为数组有序,说明右侧的数字过大,所以下标左移,故而执行end–
- sum < 0,因为数组有序,说明左侧的数字过小,所以下标右移,所以执行begin++
- 因为两层的遍历时间复杂度为O(n^2),O(n*logn) + O(n^2) = O(n^2),所以总体时间复杂度为O(n^2)

代码:

public class Solution {      public List<List<Integer>> threeSum(int[] nums) {          List<List<Integer>> res = new ArrayList<List<Integer>>();          int len=nums.length;          if(len<3)return res;          Arrays.sort(nums);          for(int i=0;i<len;i++){              if(nums[i]>0)break;              if(i>0 && nums[i]==nums[i-1])continue;              int begin=i+1,end=len-1;              while(begin<end){                  int sum=nums[i]+nums[begin]+nums[end];                  if(sum==0){                      List<Integer> list = new ArrayList<Integer>();                      list.add(nums[i]);list.add(nums[begin]);list.add(nums[end]);                      res.add(list);                      begin++;end--;                      while(begin<end && nums[begin]==nums[begin-1])begin++;                      while(begin<end && nums[end]==nums[end+1])end--;                  }else if(sum>0)end--;                  else begin++;              }          }          return res;      }  }

参考资料

http://blog.csdn.net/runningtortoises/article/details/45604601

原创粉丝点击