LeetCode15 3Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

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

双指针法,先排序,注意去除重复值

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 2; i++){
            int target = -nums[i];
            int front = i + 1;
            int back = nums.length - 1;
            while(front < back){
                if(nums[front] + nums[back] < target){
                    front++;
                }
                else if(nums[front] + nums[back] > target){
                    back--;
                }
                else{
                    res.add(Arrays.asList(nums[i],nums[front],nums[back]));
                    while(front < back && nums[front+1] == nums[front]) front++;
                    while(front < back && nums[back-1] == nums[back]) back--;
                    front++;
                    back--;
                }
            }
            while(i+1 < nums.length && nums[i+1] == nums[i]) i++;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/84999893