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.
For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

思路:这道题目的难点在于处理duplicate,给的数组可能会出现duplicate。 先sort下这个歌数组,时间复杂度为O(nlogn)。 把3sum的问题拆分为2sum问题, 可以遍历数组的时候,指针i指向的为target=nums[i], 那么剩下就是再找两个元素的和为-target的问题。 由于存在重复元素,用hashmap做起来很不方便,可以用两指针来从两端往中间找。 注意边界条件的判定跟duplicate。 时间复杂度为O(nlogn) + O(n2)

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (nums == null || nums.length < 3) return res;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue; // skip duplicates
            int target = -nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                if (nums[left] + nums[right] < target) {
                    left++;
                } else if (nums[left] + nums[right] > target){
                    right--;
                } else {
                    res.add(Arrays.asList( nums[i],nums[left], nums[right]));

                    while(left < right && nums[left] == nums[left + 1]) { // skip duplicates
                        left++;
                    }
                    while(left < right && nums[right] == nums[right - 1]) { // skip duplicates
                        right--;
                    }
                    left++;
                    right--;
                }
            }
        }
        return res;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s