算法刷题记录-数组之和

发布时间 2023-11-29 20:47:07作者: 工带菜鸡

算法刷题记录-数组之和

四数相加Ⅱ

给你四个整数数组 nums1nums2nums3nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例 1:

输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

示例 2:

输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1

思路:暴力解法,四个for循环,但是会超时间限制

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    int res=0;
    for (int i = 0; i < nums1.length; i++) {
        for (int j = 0; j < nums2.length; j++) {
            for (int k = 0; k < nums3.length; k++) {
                for (int l = 0; l < nums4.length; l++) {
                    if(nums1[i]+nums2[j]+nums3[k]+nums4[l]==0)res+=1
                }
            }
        }
    }

    return res;
}

优化思路1:把四个数组合成两个数组,然后两个数组进行判断

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    int res=0;
    int[] nums1verge=new int[nums1.length*nums2.length];
    int[] nums2verge=new int[nums1.length*nums2.length];
    int index=0;
    for (int i = 0; i < nums1.length; i++) {
        for (int j = 0; j < nums2.length; j++) {
            nums1verge[index]=nums1[i]+nums2[j];
            index++;
        }
    }

    index=0;
    for (int i = 0; i < nums3.length; i++) {
        for (int j = 0; j < nums4.length; j++) {
            nums2verge[index]=nums3[i]+nums4[j];
            index++;
        }
    }
    HashMap<Integer,Integer> map1=new HashMap<>();
    for(int i:nums1verge){
        if(!map1.containsKey(i)){
            map1.put(i,1);
        }
        else {
            map1.put(i,map1.get(i)+1);
        }
    }

    HashMap<Integer,Integer> map2=new HashMap<>();
    for(int i:nums2verge){
        if(!map2.containsKey(i)){
            map2.put(i,1);
        }
        else {
            map2.put(i,map2.get(i)+1);
        }
    }
    for(Integer i:map1.keySet()){
        if(map2.containsKey(0-i))res+=(map1.get(i)*map2.get(0-i));
    }

    return res;
}

优化二:只用一个map:

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    int res=0;
    HashMap<Integer,Integer> map1=new HashMap<>();
    for (int i = 0; i < nums1.length; i++) {
        for (int j = 0; j < nums2.length; j++) {
            int sum=nums1[i]+nums2[j];
            if(!map1.containsKey(sum)){
                map1.put(sum,1);
            }
            else {
                map1.put(sum,map1.get(sum)+1);
            }
        }
    }

    for (int i = 0; i < nums3.length; i++) {
        for (int j = 0; j < nums4.length; j++) {
            int sum=nums3[i]+nums4[j];
            if(map1.containsKey(0-sum))res+=map1.get(0-sum);
        }
    }

    return res;
}

三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != kj != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。

示例 2:

输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。

示例 3:

输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。

解法一:暴力解法,一个个三元组判断,但是会超时间

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> res=new ArrayList<>();
    int i=0;int j=1;int k=2;
    if(nums.length<3)return res;
    if(nums.length==3){
        if(nums[i]+nums[j]+nums[k]==0){
            List<Integer> temp=new ArrayList<>();
            temp.add(nums[i]);temp.add(nums[j]);temp.add(nums[k]);
            res.add(temp);
        }
        return res;
    }
    while (i<=nums.length-3){
        if(nums[i]+nums[j]+nums[k]==0){
            List<Integer> temp=new ArrayList<>();
            temp.add(nums[i]);temp.add(nums[j]);temp.add(nums[k]);
            Collections.sort(temp);
            if(!res.contains(temp))res.add(temp);
        }
        if(k!=nums.length-1)k++;
        else if(j!=nums.length-2){
            j++;
            k=j+1;
        }
        else {
            i++;
            j=i+1;
            k=i+2;
        }
    }
    return res;
}

思路二:用一个双重循环遍历,得到任意两个位置的和,在用一个for循环找解但还是超了

public List<List<Integer>> threeSum(int[] nums) {
    
    List<List<Integer>> res=new ArrayList<>();
    Set<List<Integer>> res1=new HashSet<>();
    HashMap<Integer,Set> map=new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        for (int j = i+1; j < nums.length; j++) {
            if(i!=j){
                Set<List<Integer>> temp=new HashSet<>();
                List<Integer> templist=new ArrayList<>();
                templist.add(i);templist.add(j);
                temp.add(templist);
                if(!map.containsKey(nums[i]+nums[j])) {
                    map.put(nums[i] + nums[j], temp);
                }
                else {
                    Set<List<Integer>> temp1=map.get(nums[i]+nums[j]);
                    temp1.add(templist);
                    map.put(nums[i]+nums[j],temp1);
                }
            }
        }
    }
    HashMap<Integer,Boolean> flag=new HashMap<>();
    for(int i:nums){
        flag.put(i,true);
    }
    for (int i = 0; i < nums.length; i++) {
        if(map.containsKey(0-nums[i]) & flag.get(nums[i])){
            Set<List<Integer>> temp1=map.get(0-nums[i]);
            int templen=res.size();
            for(List<Integer> templist:temp1){
                if(!templist.contains(i)){
                    List<Integer> restemp=new ArrayList<>();
                    restemp.add(nums[i]);
                    restemp.add(nums[templist.get(0)]);
                    restemp.add(nums[templist.get(1)]);
                    Collections.sort(restemp);
                    res1.add(restemp);
                }
            }
            if(res.size()!=templen)flag.put(nums[i],false);
        }
    }
    res=new ArrayList<>(res1);
    return res;
}

思路三:算法流程:
特判,对于数组长度 nnn,如果数组为 nullnullnull 或者数组长度小于 333,返回 [][][]。
对数组进行排序。
遍历排序后数组:
若 nums[i]>0nums[i]>0nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 000,直接返回结果。
对于重复元素:跳过,避免出现重复解
令左指针 L=i+1L=i+1L=i+1,右指针 R=n−1R=n-1R=n−1,当 L<RL<RL<R 时,执行循环:
当 nums[i]+nums[L]+nums[R]0nums[i]+nums[L]+nums[R]0nums[i]+nums[L]+nums[R]==0,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,RL,RL,R 移到下一位置,寻找新的解
若和大于 000,说明 nums[R]nums[R]nums[R] 太大,RRR 左移
若和小于 000,说明 nums[L]nums[L]nums[L] 太小,LLL 右移
复杂度分析

作者:吴彦祖
链接:https://leetcode.cn/problems/3sum/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> res=new ArrayList<>();
    Set<List<Integer>> res1=new HashSet<>();
    if(nums.length<3)return res;
    else if(nums.length==3){
        if(nums[0]+nums[1]+nums[2]==0){
            List<Integer> temp=new ArrayList<>();
            temp.add(nums[0]);
            temp.add(nums[1]);
            temp.add(nums[2]);
            res.add(temp);
            return res;
        }
    }
    for (int i = 0; i < nums.length; i++) {
        if(nums[i]>0)break;
        if(i>0){
            if(nums[i]==nums[i-1])continue;
        }
        int low=i+1;
        int high=nums.length-1;
        while (low<high){
            if(nums[i]+nums[low]+nums[high]==0){
                List<Integer> temp=new ArrayList<>();
                temp.add(nums[i]);
                temp.add(nums[low]);
                temp.add(nums[high]);
                res1.add(temp);
                while (low<high){
                    if( nums[low]==nums[low+1])low++;
                    else break;
                }
                while (low<high){
                    if( nums[high]==nums[high-1])high--;
                    else break;
                }
                high--;low++;

            }
            else if(nums[i]+nums[low]+nums[high]<0){
                   low++;
            }
            else {
                high--;
            }
        }
    }
    res=new ArrayList<>(res1);
    return res;
}

四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):

  • 0 <= a, b, c, d < n
  • abcd 互不相同
  • nums[a] + nums[b] + nums[c] + nums[d] == target

你可以按 任意顺序 返回答案 。

示例 1:

输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

示例 2:

输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]

思路:在三数之和的基础上在此添加一个循环

public List<List<Integer>> fourSum(int[] nums, int target) {
    Arrays.sort(nums);
    List<List<Integer>> res=new ArrayList<>();
    Set<List<Integer>> res1=new HashSet<>();
    if(nums.length<4)return res;
    else if(nums.length==4){
        if(nums[0]+nums[1]+nums[2]+nums[3]==target & nums[0]+nums[1]+nums[2]+nums[3]>nums[0]){
            List<Integer> temp=new ArrayList<>();
            temp.add(nums[0]);
            temp.add(nums[1]);
            temp.add(nums[2]);
            temp.add(nums[3]);
            res.add(temp);
            return res;
        }
    }
    for (int i = 0; i < nums.length-1; i++) {
        for (int j = i+1; j <nums.length ; j++) {
            if(nums[i]+nums[j]>target && nums[j]>=0)break;
            if(i>0){
                if(nums[i]==nums[i-1])continue;
            }
            int low=j+1;
            int high=nums.length-1;
            while (low<high){
                if(nums[i]+nums[j]+nums[low]+nums[high]==target){
                    List<Integer> temp=new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(nums[low]);
                    temp.add(nums[high]);
                    res1.add(temp);
                    while (low<high){
                        if( nums[low]==nums[low+1])low++;
                        else break;
                    }
                    while (low<high){
                        if( nums[high]==nums[high-1])high--;
                        else break;
                    }
                    high--;low++;

                }
                else if(nums[i]+nums[j]+nums[low]+nums[high]<target){
                    low++;
                }
                else {
                    high--;
                }
            }
        }

    }
    res=new ArrayList<>(res1);
    return res;
}

有一种情况需要注意,[1000000000,1000000000,1000000000,1000000000] -294967296,理论来说是没有结果满足的,但是4个1000000000相加超出Int上限,最终结果刚好等于-294967296,因此需要加一个判断& nums[0]+nums[1]+nums[2]+nums[3]>nums[0]