代码随想录算法训练营第7天 | Hash Table - 02


I. Common Java Operations

  • Sort an array: Array.sort(arrayname)
  • Iterate through a string/Convert string into a char array: char i : str.toCharArray()
  • Initialise double array list:
    List<List<Integer>> res = new ArrayList<>();
    res.add(new ArrayList<>());
    res.get(0).add(10);
  • When fail in very large number, decalre and cast the number into long: long sum = (long) nums[i] + nums[left] + nums[right];

II. Leetcode Exercises

(Medium) 454. 4Sum II

(Link)

Method: Hashmap
Time complexity: O ( n 2 ) O(n^2) O(n2), comapre with brute force O ( n 4 ) O(n^4) O(n4)

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i : nums1) {
            for (int j : nums2) {
                int sum = i + j;
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        for (int i : nums3) {
            for (int j : nums4) {
                res += map.getOrDefault(0 - i - j, 0);
            }
        }
        return res;
    }
}

(Easy) 383. Ransom Note

(Link)
Method: HashMap, Array(more efficient)
Time complexity: O ( n ) O(n) O(n)

Method 1: Array (recommended)

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        // shortcut
        if (ransomNote.length() > magazine.length()) {
            return false;
        }
        int[] record = new int[26];
        for(char c : magazine.toCharArray()){
            record[c - 'a'] += 1;
        }
        for(char c : ransomNote.toCharArray()){
            record[c - 'a'] -= 1;
        }
        for(int i : record){
            if(i < 0){
                return false;
            }
        }
        return true;
    }
}

Method 2: Hashmap

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
      Map<Character, Integer> map = new HashMap<>();
      for (Character i : magazine.toCharArray()) {
        map.put(i, map.getOrDefault(i, 0) + 1);
      }
      for (Character j : ransomNote.toCharArray()) {
        if (map.containsKey(j) && map.get(j) > 0) {
          map.put(j, map.get(j) - 1);
        } else {
          return false;
        }
      }
      return true;
    }
}

(Medium) 15. 3Sum

(Link)

Method: 2 pointers
Time complexity: O ( n 2 ) O(n^2) O(n2), comapred with brute force O ( n 3 ) O(n^3) O(n3)

3sum

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            // Make sure no duplicated values in the combination
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[left]);
                    temp.add(nums[right]);
                    res.add(temp);
                    // Make sure no duplicated values in the combination
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    while (left < right && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                } else if (sum > 0) {
                    right--;
                } else {
                    left++;
                }
            }
        }
        return res;
    }
}

(Medium) 18. 4Sum

(Link)

Method: 3 pointers
Time complexity: O ( n 3 ) O(n^3) O(n3), comapred with brute force O ( n 4 ) O(n^4) O(n4)

4sum

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
      List<List<Integer>> res = new ArrayList<>();
      Arrays.sort(nums);
      
      for (int i = 0; i < nums.length - 3; i++) {
        for (int j = i + 1; j < nums.length - 2; j++) {
          int left = j + 1;
          int right = nums.length - 1;

          while (left < right) {
            long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
            if (sum == target) {
              List<Integer> temp = new ArrayList<>();
              temp.add(nums[i]);
              temp.add(nums[j]);
              temp.add(nums[left]);
              temp.add(nums[right]);
              res.add(temp);
              while (right - 1 >= 0 && nums[right - 1] == nums[right]) {right--;}
              while (left + 1 < nums.length && nums[left + 1] == nums[left]) {left++;}
              left++;
              right--;
            } else if (sum > target) {
              right--;
            } else {
              left++;
            }
          }
          // Jump to the next number after the last two pointer searching
          while (j + 1 < nums.length - 2 && nums[j + 1] == nums[j]) {j++;}
        }
        // Jump to the next number after the last three pointer searching
        while (i + 1 < nums.length - 3 && nums[i + 1] == nums[i]) {i++;}
      }
      return res;
    }
}

Notes:

  • Fail test casse: nums = [1000000000,1000000000,1000000000,1000000000], target = -294967296, since the input contains very large numbers, the code encounters integer overflow when computing the sum --> should decalre and cast the sum as long
  • Handle duplicated values in the array: duplcates can appear on num[a] with num[b], however it can’t be counted twice on nums[a] --> should be careful with when to skip the duplicatd pointer index
    • Test Case 1:
      • Input: nums = [1,0,-1,0,-2,2], target = 0
      • Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
    • Test Case 2:
      • Input: nums = [2,2,2,2,2], target = 8
      • Output: [[2,2,2,2]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值