LeetCode--No.15--3Sum

早上睡醒了不能玩手机啊,晚上睡觉的时候手机还是要放得远一点。

抄了一道3sum. 有机会复习一下吧。
感觉以后即使用最笨的方法,也要写出来跑一下才可以。
要复习一下不同数据结构之间的转换,晚上总结一下。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0)   return res;
        Arrays.sort(nums);
        HashMap<Integer, Integer> map = new HashMap<>();
        HashSet<List<Integer>> set = new HashSet<>();
        for(int i = 0; i < nums.length; i++){
            map.put(nums[i], i);
        }
        for(int i = 0; i < nums.length - 2; i++){
            for (int j = i+1; j < nums.length - 1; j++){
                if (map.containsKey(0 - nums[i] - nums[j]) && map.get(0 - nums[i] - nums[j]) > j){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[map.get(0 - nums[i] - nums[j])]);
                    set.add(list);
                }
            }
        }
        for(List<Integer> list : set){
            res.add(list);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/sophia_tone2w/article/details/89929012