15. 3Sum

题目:

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)

链接: http://leetcode.com/problems/3sum/

题解:

3 pointers,注意处理重复的情况。

Time Complexity - O(n2), Space Complexity - O(1)

public class Solution {

    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        if(num.length < 3)

            return result;

        Arrays.sort(num);

        

        for(int start = 0; start < num.length - 2; start ++){

            if(start > 0 && num[start] == num[start - 1])

                continue;

            int left = start + 1, right = num.length - 1;

            

            while(left < right){

                int sum = num[start] + num[left] + num[right];

                if(sum == 0){

                    ArrayList<Integer> list = new ArrayList<Integer>();

                    list.add(num[start]);

                    list.add(num[left]);

                    list.add(num[right]);

                    result.add(list);

                    left ++;

                    right --;

                    while(left < right && num[left] == num[left - 1])

                        left ++;

                    while(left < right && num[right] == num[right + 1])

                        right --;

                } else if (sum < 0){

                    left ++;

                } else {

                    right --;

                }

            }

        }

        

        return result;

    }

}

 

你可能感兴趣的:(SUM)