二、三、四数之和

一、二数之和

在这里插入图片描述
如果使用暴力的方法,需要两重循环,也就是O(n2)。
所以,我们可以使用Hash表来降低时间复杂度。因为target是固定的,而数组中的各个元素也是固定的,所以,对于每个nums[i]来说,可以与之匹配的另一个数也是固定的数量。
所以,我们可以将所有的target-nums[i]存入hash表中,如果nums[j]存在于hash表中,说明某个target-nums[i]=nums[j],就可以得到结果了。
此处由于只有唯一的一组结果,也可以使用双指针来降低时间复杂度。
如果有多组结果,双指针可能会漏掉一些情况。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> numsMap = new HashMap<>();
        for(int i = 0;i< nums.length;i++){
            int other = target-nums[i];
            if(numsMap.containsKey(other)){
                return new int[] {numsMap.get(other),i};
            }
            numsMap.put(nums[i],i);
        }
        //throw new IllegalArgumentException("No two sum solution");
        return new int[0];
    }
}

二、大餐计数

在这里插入图片描述
这个题思路同两数之和,只是target由原来的n变为了现在的2的幂,由于提示中给出了deliciousness[i]最大为220,所以美味程度之和最大为221
如果使用暴力,时间复杂度为O(n2),所以,和两数之和一样,可以使用HashMap来存储target - deliciousness[i],这样就可以将O(n)的匹配时间降低为O(1)。同时value由原来的下标改为存储相同元素的数目。

class Solution {
    public int countPairs(int[] deliciousness) {
        Map<Integer, Integer> map = new HashMap<>();
        int result = 0;
        int max = (int)Math.pow(2, 22);
        int mod = (int)(Math.pow(10, 9) + 7);

        map.put(deliciousness[0], 1);

        for(int i = 1; i < deliciousness.length; i++) {
            for(int j = 1; j < max; j *= 2) {
                if(map.containsKey(j - deliciousness[i])) {
                    result = (result + map.get(j - deliciousness[i])) % mod;
                }
            }
            map.put(deliciousness[i], map.getOrDefault(deliciousness[i], 0) + 1);
        }

        return result;
    }
}

三、三数之和

在这里插入图片描述
可以使用暴力,遍历所有的a,b,c的组合,但这样时间复杂度为O(n3)。
所以,可以两数之和的方法,使用HashMap存储target - a,然后使用两层循环来匹配b和c,这样可以使得复杂度降为O(n2),但是由于是奇数项,所以b和c循环的时候,可能会产生重复使用a的情况。同时不允许出现重复的情况。
所以,不使用hashMap,而采用双指针来降低时间复杂度,对于每个target-a,匹配b和c,可以用一个指针指向最左端,一个指向最右端,判断两者之和是否大于target-a,如果是的话,那么右指针减小,如果和相等,那么加入结果集,左指针加1,由于是有序的,左指针增大,说明b增大了,c必然减小,右指针继续-1,直到两个指针指向同一个元素。这样也将时间复杂度降为O(n2)。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        int length = nums.length;
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        //排序
        Arrays.sort(nums);

        for(int i = 0;i<length;i++){
            //每次开头的数要和上一次的不一样---去掉重复的
            if(i >0 && nums[i] == nums[i-1]){
                continue;
            }
            int k = length - 1;
            int target = -nums[i];
            for(int j = i + 1;j<length;j++){
                 //去掉重复的
                if(j > i + 1 && nums[j] == nums[j-1]){
                    continue;
                }
                while(j<k && nums[j] + nums[k] > target){
                    k--;
                }
                if(j == k){
                    break;
                }
                if(nums[j] + nums[k] == target){
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    res.add(list);
                }
            }
        }
        return res;
    }
}

四、四数之和

在这里插入图片描述
思路同三数之和,固定target-a,再固定target - a - b,双指针求c和d。
(可以使用HashMap来解决吗?即a,b循环,判断是否存在target-a-b在Map中,不存在则放入hashMap,否则计数++,如果是求组合数目的话,我觉得应该可以。)
时间复杂度为O(n3)

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {

       List<List<Integer>> res = new ArrayList<List<Integer>>();
       Arrays.sort(nums);
       int len = nums.length;
       for(int i = 0;i<len;i++){
           if(i>0 && nums[i] == nums[i-1]){
               continue;
           }
           int tar = target - nums[i];
           for(int j = i + 1;j<len;j++){
               if( j >i+1 && nums[j] == nums[j-1]){
                   continue;
               }
               int tar2 = tar - nums[j];
               int l = len - 1;
               for(int k = j +1;k<len;k++){
                   if( k > j+1 && nums[k] == nums[k-1]){
                       continue;
                   }
                   while(k < l && nums[k] + nums[l] > tar2){
                       l--;
                   }
                   if(k==l){
                       break;
                   }
                   if(nums[k] + nums[l] == tar2){
                       List<Integer> list = new ArrayList<Integer>();
                       list.add(nums[i]);
                       list.add(nums[j]);
                       list.add(nums[k]);
                       list.add(nums[l]);
                       res.add(list);
                   }
               }
           }
       }
       return res;
    }
}

五、最接近的三数之和

在这里插入图片描述
由三数之和求a+b+c = target,变为a+b+c最接近target。

暴力的话,是O(n3),所以使用和三数之和类似的方法来降低时间复杂度,使用双指针,l指向b,r指向c,如果l+r > target,则r减1,如果小于则 l 加1。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //min表示当前与target最接近的三数之和
        //res = Math.min(min,Math.abs(target-sum))  sum为当前三个之和

        Arrays.sort(nums);
        int len = nums.length;
        int res = 1000000;
        for(int i = 0;i<len;i++){
            if(i >0 && nums[i] == nums[i-1]){
                continue;
            }
            //int tar = target - nums[i];
            int j = i+1;
            int k = len - 1;
            int sum = 0;
            while(j < k){
                sum = nums[j] + nums[k] + nums[i];
                if(sum == target){
                    return target;
                }
                if(Math.abs(res-target) > Math.abs(sum  - target)){
                    res = sum;
                } 
                if(sum > target){
                    //移动值大的那个,即k
                    k--;
                }else{
                    //移动值大的那个,即k
                    j++;
                }
            }
        }
        return res;
    }
}

六、三数之和的多种可能

在这里插入图片描述
此题和三数之和基本一样,只是由原来的求三个数的不同的组合改为求所有的a,b,c组合(只要下标不同即可)的数量。使用双指针则会忽视掉一些重复的情况,所以要优化为使用三指针。

如果是四个数的和等于target,且只要下标不同,则认为形成的组合就不同的话,可以使用双重循环+HashMap的方式。(类比大餐计数,个人猜测。。。)

class Solution {
    public int threeSumMulti(int[] A, int target) {
        int MOD = 1_000_000_007;
        long ans = 0;
        Arrays.sort(A);

        for (int i = 0; i < A.length; ++i) {
            // We'll try to find the number of i < j < k
            // with A[j] + A[k] == T, where T = target - A[i].

            // The below is a "two sum with multiplicity".
            int T = target - A[i];
            int j = i+1, k = A.length - 1;

            while (j < k) {
                // These steps proceed as in a typical two-sum.
                if (A[j] + A[k] < T)
                    j++;
                else if (A[j] + A[k] > T)
                    k--;
                else if (A[j] != A[k]) {  // We have A[j] + A[k] == T.
                    // Let's count "left": the number of A[j] == A[j+1] == A[j+2] == ...
                    // And similarly for "right".
                    int left = 1, right = 1;
                    while (j+1 < k && A[j] == A[j+1]) {
                        left++;
                        j++;
                    }
                    while (k-1 > j && A[k] == A[k-1]) {
                        right++;
                        k--;
                    }

                    ans += left * right;
                    ans %= MOD;
                    j++;
                    k--;
                } else {
                    // M = k - j + 1
                    // We contributed M * (M-1) / 2 pairs.
                    ans += (k-j+1) * (k-j) / 2;
                    ans %= MOD;
                    break;
                }
            }
        }

        return (int) ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值