代码随想录算法训练营第七天|哈希表| 454.四数相加II、383. 赎金信、 15. 三数之和、 18. 四数之和

代码随想录算法训练营第七天|哈希表| 454.四数相加II、383. 赎金信、 15. 三数之和、 18. 四数之和

454.四数相加II

题目链接: 454.四数相加
思想:

这道题我没有做出来,使用暴力求解会超时!

代码随想录的处理方法:

因为我们只需要出现的次数就可以,所以我们先计算nums1和nums2这两个数组的求和情况,并把和作为map的key, 和出现的次数作为value

再计算nums3和nums4这两个数组求和的情况,用0减去求和结果并去map中寻找有无key,有的话把其value也就是出现的次数加入到总次数中

总而言之,两两处理, 用哈希map作为一组数组的查询表,然后另一组去查询

代码:

python

class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type nums3: List[int]
        :type nums4: List[int]
        :rtype: int
        """
        mydict = dict()

        count = 0

        for a in nums1:
            for b in nums2:
                if a+b in mydict:
                    mydict[a+b] += 1
                else:
                    mydict[a+b] = 1
        
        for c in nums3:
            for d in nums4:
                if 0-(c+d) in mydict:   
                    count += mydict[0-(c+d)]
                else:
                    pass

        return count

java

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map map = new HashMap<>();
        int temp;
        int res = 0;
        //统计两个数组中的元素之和,同时统计出现的次数,放入map
        for (int i : nums1) {
            for (int j : nums2) {
                temp = i + j;
                if (map.containsKey(temp)) {
                    map.put(temp, map.get(temp) + 1);
                } else {
                    map.put(temp, 1);
                }
            }
        }
        //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
        for (int i : nums3) {
            for (int j : nums4) {
                temp = i + j;
                if (map.containsKey(0 - temp)) {
                    res += map.get(0 - temp);
                }
            }
        }
        return res;
    }
}

383. 赎金信

题目链接: 383. 赎金信

  • 自己做:

这道题没什么可说的,跟之前的题目差不多

代码:

python

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        # 思想:
        '''
        将magazine用哈希表表示,其中key为字符,value为字符出现的次数,然后循环ransomNote去哈希表中查询有无
        '''
        mydict = dict()

        for char in magazine:
            if char in mydict:
                mydict[char] += 1
            else:
                mydict[char] = 1
        
        for char in ransomNote:
            if char in mydict and mydict[char] > 0:
                mydict[char] -= 1
            else:
                return False

        return True
  • 代码随想录

思想:

  1. 因题目中说ransomNote 和 magazine 由小写英文字母组成,所以可以用数组来做,index表示字母,元素表示字母出现的次数

  2. “magazine 中的每个字符只能在 ransomNote 中使用一次”,所以要统计元素出现的次数

代码:

python

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ransom_count = [0] * 26
        magazine_count = [0] * 26
        for c in ransomNote:
            ransom_count[ord(c) - ord('a')] += 1
        for c in magazine:
            magazine_count[ord(c) - ord('a')] += 1
        return all(ransom_count[i] <= magazine_count[i] for i in range(26))

java

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        // 定义一个哈希映射数组
        int[] record = new int[26];

        // 遍历
        for(char c : magazine.toCharArray()){
            record[c - 'a'] += 1;
        }

        for(char c : ransomNote.toCharArray()){
            record[c - 'a'] -= 1;
        }
        
        // 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符
        for(int i : record){
            if(i < 0){
                return false;
            }
        }

        return true;
    }
}

15. 三数之和

题目链接: 15. 三数之和
思想:

有点难,没有做出来

先排序再用双指针法,演示过程如下:
代码随想录算法训练营第七天|哈希表| 454.四数相加II、383. 赎金信、 15. 三数之和、 18. 四数之和_第1张图片
需要注意的点:

  1. 题中说,答案中不可以包含重复的三元组,如何去除重复的三元组呢?

nums[i] == nums[i-1] 我们就跳过i,因为在i-1处就已经考虑到所有的情况并将符合三数之和为0的三元组加入到结果列表中。

同时,left 和 right在向中间移动时,在符合三数之和为0的情况下,如果出现nums[right] == nums[right-1] 和 nums[left] == nums[left+1]情况,也需要跳过,如果不跳过,结果列表中就会出现重复的三元组。

  1. 要排序,为什么呢?

目的是让相等的数字挨在一块儿,后续方便去重。

  1. 这种方法要记住:for循环的i,再设置left和right指针来筛选符合条件的三元组

代码:

python

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        ''''
        条件:
        1. i + j + k = 0
        2. i,j,k互相不同
        3. [i,j,k]不重复
        思想:
        1. 先排序(目的是让相等的数字挨在一块儿,后续方便去重)
        2. 再用双指针法,固定一个不动i,再用left和right指针寻找合适的j和k
        '''
        nums.sort()

        result = []

        for i in range(0, len(nums)-1-1):
            if nums[i] > 0:
                return []
            
            if i > 0 and nums[i] == nums[i-1]:
                continue

            left = i+1
            right = len(nums)-1

            while left < right:
                if nums[i] + nums[left] + nums[right] > 0:
                    right -= 1
                elif nums[i] + nums[left] + nums[right] < 0:
                    left += 1
                else:
                    result.append([nums[i], nums[left], nums[right]])
                    # 跳过相同的元素以避免重复
                    while right > left and nums[right] == nums[right - 1]:
                        right -= 1
                    while right > left and nums[left] == nums[left + 1]:
                        left += 1
                    left += 1
                    right -= 1
            
        return result

java

class Solution {
    public List> threeSum(int[] nums) {
        List> result = new ArrayList<>();
        Arrays.sort(nums);
	// 找出a + b + c = 0
        // a = nums[i], b = nums[left], c = nums[right]
        for (int i = 0; i < nums.length; 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 (right > left) {
                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 (right > left && nums[right] == nums[right - 1]) right--;
                    while (right > left && nums[left] == nums[left + 1]) left++;
                    
                    right--; 
                    left++;
                }
            }
        }
        return result;
    }
}

18. 四数之和

题目链接: 18. 四数之和

思想:

和三数之和差不多,相比三数之和只有一个i的大指针,在计算四数之和时有i, j两个指针,i和j都需要考虑去重,其他的和三指针就没什么区别了

代码:

python

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        result = []
        for i in range(0, len(nums)-1-1-1):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1, len(nums)-1-1):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                
                left = j+1
                right = len(nums)-1

                while left < right:
                    sum = nums[i] + nums[j] + nums[left] + nums[right]
                    if sum < target:
                        left += 1
                    elif sum > target:
                        right -= 1
                    else:
                        result.append([nums[i], nums[j], nums[left], nums[right]])
                        while left < right and nums[left] == nums[left+1]:
                            left += 1
                        while left < right and nums[right] == nums[right-1]:
                            right -= 1
                        left += 1
                        right -= 1
        
        return result

java

class Solution {
    public List> fourSum(int[] nums, int target) {
        List> result = new ArrayList<>();
        Arrays.sort(nums);
       
        for (int i = 0; i < nums.length; i++) {
		
            // nums[i] > target 直接返回, 剪枝操作
            if (nums[i] > 0 && nums[i] > target) {
                return result;
            }
		
            if (i > 0 && nums[i - 1] == nums[i]) {    // 对nums[i]去重
                continue;
            }
            
            for (int j = i + 1; j < nums.length; j++) {

                if (j > i + 1 && nums[j - 1] == nums[j]) {  // 对nums[j]去重
                    continue;
                }

                int left = j + 1;
                int right = nums.length - 1;
                while (right > left) {
		    // nums[k] + nums[i] + nums[left] + nums[right] > target int会溢出
                    long sum = (long) 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]));
                        // 对nums[left]和nums[right]去重
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;

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

总结:

你可能感兴趣的:(算法训练营刷题,算法)