代码随想录 D7 | 454. 四数相加 383.赎金信 15.三数之和 18. 四数之和

1. 454. 四数相加||

  • 题目链接:454. 四数相加 II - 力扣(LeetCode)
  • 题意:四个长度为n的整数数组,计算有多少个元组可以满足和为0
  • 思路:先将前两个数组的和做成map={key:sum(num1[i]+num2[i], value:times),再将后两个数两个数组的和与map相比较,如果= -key in map 则次数+value个
  • 复杂度:time: O(n^2) Space: O(n^2)
  • 代码:
class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        // 思路:两两计算
        Map<Integer, Integer> sum1and2 = new HashMap<>();

        // array 1+2
        for(int i=0; i<nums1.length; i++){
            for(int j=0; j<nums2.length; j++){
                    sum1and2.put(nums1[i] + nums2[j], sum1and2.getOrDefault(nums1[i] + nums2[j], 0) + 1);
            }
        }

        // array 3+4
        int count = 0;
        int[] add3and4 = new int[nums3.length*nums4.length];
        for(int i=0; i<nums3.length; i++){
            for(int j=0; j<nums4.length; j++){
                int complement = -nums3[i] - nums4[j];
                if(sum1and2.containsKey(complement)){
                    count += sum1and2.get(complement);}
            }
        }


        return count;
    }
}

2. 383. 赎金信

  • 链接:383. 赎金信 - Medium​​​​​​ 
  • 题目含义:判断字符串t中的元素能不能由magazine里面的字符构成,可以则返回true,不可以返回false,每个元素只能用一次
  • 思路: 首先由于这两个字符串都由小写英文字母组成,所以可以考虑数组的方法,其次,也可以考虑用map构建一个字符串。前者会更快一些
  • 复杂度:空间O(1),时间0(n)
  • 代码实现:
  • class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            //用数组的方法
            int[] dictionary = new int[26];
            // magazine的值存入哈希表
            char[] aimed = magazine.toCharArray();
            for(char alphabet : aimed){
                int index = alphabet - 'a';
                dictionary[index]++;
            }
            // 将哈希表与ransomNote进行比较
            char[] compared = ransomNote.toCharArray();
            for(char alphabet : compared){
                int index = alphabet - 'a';
                if(dictionary[index] == 0) return false;
                else
                    dictionary[index]--;
            }
            return true;
        }
    }

    3. 15. 三数之和

    • 题目链接:15. 三数之和 - 中等- 力扣(LeetCode)
    • 题意:给定一个整数数组num,判断这个数组里是否存在不重复的三元组,使得三者的和为0,并且打印出符合条件的所有三元组的数组
    • 思路:由于是同一个数组内的不同元素,所以需要考虑到去重的问题。这题为了降低复杂度,采用了双指针的方法,首先对数组进行了排序,其次采用双指针法处理最后一次的遍历。注意:一开始去重采用的是判断List.contains()的方法,但是这样增加了复杂度,并且影响了通过时间。因此需要采用更方便的去重方式
      • 去重:这里采用的方式是与前一个元素相比较,如果和前一个元素相同,则代表有重复的部分,此处的去重需要对三指针分别去重
    • 复杂度:由于使用了双指针法,因此可以减少一次n,复杂度为O(n^2),空间复杂度O(1)
    • 代码:        
    • class Solution {
          public List<List<Integer>> threeSum(int[] nums) {
              List<List<Integer>> result= new ArrayList<>();                  
              Arrays.sort(nums);
      
              if(nums.length < 3) return result;
              for(int i = 0; i < nums.length-2; i++){
                  if(nums[i] > 0) return result;
                  //非常关键的去重步骤
                  if (i > 0 && nums[i] == nums[i - 1]) {  // 去重a
                      continue;
                  }
                  int left = i + 1;
                  int right = nums.length - 1;
                  while(left < right){
                      if(nums[i]+nums[right]+nums[left] > 0){
                          right--;
                      }
                      else if(nums[i]+nums[right]+nums[left] < 0)
                          left++;
                      else{
                          List<Integer> current = new ArrayList<>();
                          current.add(nums[i]);
                          current.add(nums[left]);
                          current.add(nums[right]);
                          result.add(current);
                          // 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
                          while (right > left && nums[right] == nums[right - 1]) right--;
                          while (right > left && nums[left] == nums[left + 1]) left++;
                          left++;
                          right--;
                      }
                  }
              }
              return result;
      
          }
      }

4. 18.四数之和

  • 链接:18. 四数之和 - Medium- 力扣(LeetCode)
  • 题意:和上一道题差不多,只不过是四个数,且和变成了target
  • 思路:和上一题的总体思路是一样的,但是要注意一个去重问题,就是对第二个元素进行去重的时候,如果此时第一个元素已经发生了变化,则需要更新去重条件
  • 复杂度:O(B^3), O(1)
  • 各种各样的问题:
    1. 数组排序:Arrays.sort(nums);
    2. 数据溢出:转换为long的类型,避免溢出问题
    3. left和right指针去重问题:避免溢出的数组的情况发生
    4. index2去重问题,当index1更新为新的值的时候,就得更新去重条件了
  • 代码:
    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            // Step 1: sort the array
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<>();
            if(nums.length < 4)
                return result;
            // step 2: 
            for(int index1 = 0; index1 < nums.length - 3; index1++){
                int lastIndex1 = 0;
                if(index1>=1){
                    while(nums[index1] == nums[index1-1] && index1 < nums.length-3)
                        index1++;
                }
                for(int index2 = index1 + 1; index2 < nums.length - 2; index2++){
                    
                if(index2>=2 && ((index1 == lastIndex1)|| index1 == 0) ){
                    while(nums[index2] == nums[index2-1] && index2 < nums.length - 2)
                        index2++;
                }
                if(index1!= lastIndex1)
                    lastIndex1 = index1;
    
                    int left = index2+1;
                    int right = nums.length - 1;
    
                    while(left<right){
                        long sum = (long)nums[index1]+(long)nums[index2]+(long)nums[left]+(long)nums[right];
                        if(sum > target)
                            right--;
                        else if(sum < target)
                            left++;
                        else if(sum == target){
                            // Now get 1+2+3+4 == target
                            List<Integer> current = new ArrayList<>();
                            current.add(nums[index1]);
                            current.add(nums[index2]);
                            current.add(nums[left]);
                            current.add(nums[right]);
                            result.add(current);
                            // delete replicated index groups
                            while(nums[left] == nums[left-1] && left < nums.length-1 && left-1 > index2)
                                left++;
                            while(nums[right] == nums[right-1] && right >= 3)
                                right--;
                            
                            left++;
                            right--;
                        }
    
                    }
                }
            }
            return result;
        }
    }

    小结

    1. 总体来说是为了判断一个元素是否在集合里。数组,set,map这三种常用的哈希结构
    2. 难度不大,但是由于之前对于set和map操作不熟悉,因此遇到各种各样的问题,需要经常复习这块。
  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值