LeetCode 0015

题目链接:

https://leetcode.com/problems/3sum/description/

题意理解

在一个列表中找三个数,使得其和为0。做过2sum的朋友应该知道,假设要找出是否存在两个数的和为 sum s u m , O(n) O ( n ) 做法是边做边加到set里,读到一个新数就查一下 suma[i] s u m − a [ i ] 是否在set里面。ok,知道了2sum的做法,那么3sum呢?我们可以先排序,然后取最前面的数为基准,只要在其后面找到两个数,和是第一个数的相反数就行了。

我的代码

   public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Set<String> answers = new HashSet<>();
        if(nums.length < 3) {
            return result;
        }
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 2; i++) {
            int sum = nums[i] * -1;
            int l = i + 1;
            int r = nums.length - 1;
            if(i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            while(l < r) {
                if(nums[l] + nums[r] == sum) {
                    String hashValue = nums[i] + " " + nums[l] + " " + nums[r];
                    if(!answers.contains(hashValue)) {
                        answers.add(hashValue);
                        List<Integer> ans = new ArrayList<>();
                        ans.add(nums[i]);
                        ans.add(nums[l]);
                        ans.add(nums[r]);
                        result.add(ans);
                    }
                    l++;
                } else if(nums[l] + nums[r] < sum) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return result;
    }

解后反思

看到了一个非常快的代码,这个代码的做法是充分使用了二分查找加打表的思想,外加分类讨论,学不来。

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> threeSum(int[] nums) {
        int len = nums.length;
        if (len < 3)
            return res;

        Arrays.sort(nums);  //sort the array first

        int zeroCount; //the appearing times of 0
        int lastNeg = Arrays.binarySearch(nums, 0); //search the position of 0; it also means the position of the last negative number in array
        int firstPos = lastNeg; //the position of the first positive number in array
        if(lastNeg < 0){    //0 not found
            zeroCount = 0;
            lastNeg = -(lastNeg + 1) - 1;//see the Java api
            firstPos = lastNeg + 1;
        }
        else{               //found
            while(lastNeg > -1 && nums[lastNeg] == 0) //skip all 0
                lastNeg--;
            while(firstPos < len && nums[firstPos] == 0)
                firstPos++;
            zeroCount = firstPos - lastNeg - 1;
        }

        int min;
        int max;
        int[] hash;
        min = nums[0];
        max = nums[len - 1];
        max = Math.max(Math.abs(max), Math.abs(min)); //to allocate enough space to avoid check in if statement
        min = -max;                                
        hash = new int[max - min + 1];
        for (int v : nums) { //hash and count appearing times of every num
            hash[v - min]++;
        }

        if (zeroCount >= 3) { // (0 appears 3 times at least)
            addTriplets(0, 0, 0);
        }
        if (zeroCount > 0 ) { // (0 appears 1 times at least)
            for (int i = firstPos; i < len; i++) { //traverse all the positive numbers to see whether there is a negative number whose absolute value equals to the positive number 
                if(i > firstPos && nums[i] == nums[i - 1]) //skip the same elements
                    continue;
                if (hash[-nums[i] - min] > 0) 
                    addTriplets(0, nums[i], -nums[i]);
            }
        }

        // one positive number and two negetive numbers 
        for (int i = firstPos; i < len; i++) { //traverse all the positive numbers to see whether there are two negative numbers whose sum's absolute value equals to the positive number
            if(i > firstPos && nums[i] == nums[i - 1]) //skip the same elements
                    continue;
            int half;   //we can traverse only half of the positive numbers
            if(nums[i] % 2 != 0)
                half = -(nums[i] / 2 + 1);
            else{
                half = -(nums[i] / 2);
                if(hash[half - min] > 1)
                    addTriplets(nums[i], half, half);
            }
            for(int j = lastNeg; j > -1 && nums[j] > half; j--){
                if(j < lastNeg && nums[j] == nums[j + 1])
                    continue;
                if(hash[(-nums[i] - nums[j]) - min] > 0)
                    addTriplets(nums[i], nums[j], -nums[i] - nums[j]);
            }
        }

        // one positive number and two negetive numbers 
        for (int i = lastNeg; i > -1; i--) { //traverse all the negative numbers to see whether there are two positive numbers whose sum's absolute value equals to the negative number
            if(i < lastNeg && nums[i] == nums[i + 1])//skip the same elements
                    continue;
            int half; //we can traverse only half of the positive numbers
            if(nums[i] % 2 != 0)
                half = -(nums[i] / 2 - 1);
            else{
                half = -(nums[i] / 2);
                if(hash[half - min] > 1)
                    addTriplets(nums[i], half, half);
            }
            for(int j = firstPos; j < len && nums[j] < half; j++){
                if(j > firstPos && nums[j] == nums[j - 1])
                    continue;
                if(hash[(-nums[i] - nums[j]) - min] > 0)
                    addTriplets(nums[i], nums[j], -nums[i] - nums[j]);
            }
        }
        return res;
    }

    public void addTriplets(int a, int b, int c) {
        List<Integer> triplets = new ArrayList<>(3);
        triplets.add(a);
        triplets.add(b);
        triplets.add(c);
        res.add(triplets);
    }
}
//MaplePC
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值