Day 7 | 454. 4Sum II | 383. Ransom Note | 15. 3Sum | 18. 4Sum

本文精选了LeetCode上的多个经典算法题目,包括两数之和、三数之和、四数之和等,并提供了详细的解决方案及思路分析。

Day 1 | 704. Binary Search | 27. Remove Element | 35. Search Insert Position | 34. First and Last Position of Element in Sorted Array
Day 2 | 977. Squares of a Sorted Array | 209. Minimum Size Subarray Sum | 59. Spiral Matrix II
Day 3 | 203. Remove Linked List Elements | 707. Design Linked List | 206. Reverse Linked List
Day 4 | 24. Swap Nodes in Pairs| 19. Remove Nth Node From End of List| 160.Intersection of Two Lists
Day 6 | 242. Valid Anagram | 349. Intersection of Two Arrays | 202. Happy Numbe | 1. Two Sum


454. 4Sum II

Question Link

Solution:

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0; // count the present time of a+b+c+d = 0;
        for(int i : nums1){
            for(int j : nums2){
                int tmp = i + j;
                if(map.containsKey(tmp))
                	//use the key to store the sum of a and b
                	//use the value to keep the present time of the sum of a and b.
                    map.put(tmp, map.get(tmp)+1);
                else
                    map.put(tmp, 1);
            }
        }
        for(int i : nums3){
            for(int j : nums4){
                int tmp = i + j;
                if(map.containsKey(0-tmp))
                    count += map.get(0-tmp);
            }
        }
        return count;
    }
}

Thought:

  • Define a map, use the key to store the sum of a and b, and use the value to keep the present time of the sum of a and b
  • Define a count for counting the present time of a+b+c+d = 0
  • Iterate the nums3 and nums4, calculate the sum of c and d, that is tmp
  • If the map contains the key 0-tmp, use the count to pluse the value corresponding to the key in the map

383. Ransom Note

Question Link

Solution:

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

Thought:

  • Define an int array record for counting the presenting times of 26 characters
  • If the negative number exists, it demonstrates that at least a character exists in ransomNote but not in magazine.

15. 3Sum

Question Link

Solution:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();       
        // 排序
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            // 如果第一个数a大于0,就不可能凑成三元组了
            if(nums[i] > 0)
                break;
            // 对a去重
            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)
                    right--;
                else if(sum < 0)
                    left++;
                else{
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 对b、c去重
                    while(left < right && nums[left] == nums[left+1]) left++;
                    while(left < right && nums[right] == nums[right-1]) right--;
                    left++;
                    right--;
                }
            }
        }
        return result;
    }
}

Thought:

  • Sort the array because we adopt the Double Pointer Method
  • After sorting, if the first element is greater than 0, other parts must be greater than 0. So we can do break directly.
  • Deduplicate a
  • According to the sum of three elements, adjusts the b and c until the sum equal to 0
  • Don’t forget to deduplicate b and c

18. 4Sum

Question Link

Solution:

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0 && nums[i]>target)
                break;
            // deduplicate a
            if(i > 0 && nums[i] == nums[i-1])
                continue;
            for(int j = i+1; j < nums.length; j++){
                // deduplicate b
                if(j > i+1 && nums[j] == nums[j-1])
                    continue;
                int left = j + 1;
                int right = nums.length - 1;
                while(left < right){
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum > target)
                        right--;
                    else if(sum < target)
                        left++;
                    else {
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        // deduplicate c and d
                        while(left < right && nums[left]==nums[left+1]) left++;
                        while(left < right && nums[right]==nums[right-1])right--;

                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }
}

Thought:

  • If the first element is greater than 0 and target, other parts must be greater than 0, and the sum must be greater than target. So we can do break directly.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值