leetcode(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]
]

因为本人比较菜,所以一开始想的当然是N3的遍历,但是一个medium的题目肯定不能这么简单,所以这题就理解为成a+b = -c的题目。然后可以用双指针做,遍历num[],0-num[i]作为-c,left指针从i+1开始向右遍历,right从右开始向左遍历。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        //先排序
        Arrays.sort(nums);
        //避免重复,将获得的list先放入set中
         Set<List> sets = new HashSet<>();
        for(int i=0;i<nums.length;i++){
         //如果num[i]>0就出现不了=0的情况所以break
            if (nums[i]>0)break;
            int target = 0-nums[i];
            int j = i+1;int k = nums.length-1;//定义左右指针
            while (j<k){
                if (nums[j]+nums[k] == target){
                    List<Integer> set = new ArrayList<>();
                    set.add(nums[i]);set.add(nums[j]);set.add(nums[k]);
                    sets.add(set);
                    j++;k--;
                }
                //如果左右指针的数的sum小于target则从用更大的比较,所以j++,同理,如果小于target,则k--;
                else if (nums[j]+nums[k]<target){
                    j++;
                }
                else {
                    k--;
                }
            }
        }
        List<List<Integer>> lists = new ArrayList<>();
        for (List list: sets){
            lists.add(list);
        }
        return lists;
    }
}
发布了43 篇原创文章 · 获赞 1 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章