leetcode | 3Sum

来源:互联网 发布:ipad免越狱软件 编辑:程序博客网 时间:2024/06/06 07:27

Given an array S of n integers, are there elements abc 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)

暴力解决法是每个人都能想到的,三层for循环,时间复杂度是O(n^3),而且还要处理重复的问题,显然不是题目想要的解法。

那能不能降到O(n^2)?排序算法的时间复杂度为O(nlgn),小于O(n^2),那么我们不妨先对数组排个序。

排序之后,我们就可以对数组用两个指针分别从前后两端向中间扫描了,如果是 2Sum,我们找到两个指针之和为target就OK了,那 3Sum 类似,我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。

代码不难,先看了再说。

public class Solution {    public List<List<Integer>> list = new ArrayList<>();        public List<List<Integer>> threeSum(int[] nums) {            if (nums == null || nums.length < 3) return list;                                Arrays.sort(nums);             int len = nums.length;            for (int i=0;i<nums.length-2;i++)            {                if(i>0&&nums[i]==nums[i-1]) continue;                sum2(nums,i+1,len-1,-nums[i]);            }            return list;        }        public void sum2(int[] nums,int start,int end,int x)        {            int i = start;            int j = end;            while(i<j)            {                                if(nums[i]+nums[j]==x)                {                                        List<Integer> tmp = new ArrayList<>();                    tmp.add(nums[start-1]);                    tmp.add(nums[i]);                    tmp.add(nums[j]);                    list.add(tmp);                    while(i<j&&nums[i]==nums[i+1]) i++;                    while(i<j&&nums[j]==nums[j-1]) j--;                    i++;                    j--;                }                else if(nums[i]+nums[j]<x)                {                    i++;                }                else                {                    j--;                }            }        }}


0 0
原创粉丝点击