Day 7 哈希: 454. 四數相加 II, 383. 贖金信, 15. 三數之和, 18. 四數之和

454. 四數相加 II

  • 思路
    • example
    • 四個數組相同長度
    • 第一步:brute-force: O(n^4)
    • hash: dict
      • record[num] = freq

第二步:O(n^3)+O(n) = O(n^3)
第三步:(nums1[i]+nums2[j]) + (nums3[k]+nums4[l])O(n^2)

  • 復雜度. 時間:O(n^2), 空間: O(n^2)
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        n = len(nums1) 
        record = collections.defaultdict(int) 
        for i in range(n):
            for j in range(n):
                record[nums1[i]+nums2[j]] += 1 
        res = 0
        for k in range(n):
            for l in range(n):
                if -(nums3[k] + nums4[l]) in record:
                    res += record[-(nums3[k] + nums4[l])]
        return res 
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        record = collections.defaultdict(int)  
        for num1 in nums1:
            for num2 in nums2:
                record[num1+num2] += 1
        res = 0
        for num3 in nums3:
            for num4 in nums4:
                if record[-(num3+num4)] > 0:
                    res += record[-(num3+num4)] # !!!
        return res    

383. 贖金信

  • 思路
    • example
    • hash: dict
      • record[ch] = freq

先遍歷模式串magazine

  • 復雜度. 時間:O(n), 空間: O(n)
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        table = collections.defaultdict(int)
        for ch in magazine:
            table[ch] += 1
        for ch in ransomNote:
            table[ch] -= 1
            if table[ch] < 0:
                return False  
        return True  
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        record = collections.defaultdict(int)   
        for ch in magazine:
            record[ch] += 1 
        for ch in ransomNote:
            record[ch] -= 1
            if record[ch] < 0:
                return False  
        return True 

15. 三數之和

  • 思路
    • example
    • a + b + c = 0
    • 用hash的話去重問題更麻煩。
    • 雙指針, --><--
      • 去重:(用排序配合)
        • a: nums[i] == nums[i-1]
        • b and c: while-loop moving left and right
  • 復雜度. 時間:O(n^2), 空間: O(1)
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        res = []
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]: # 去重1
                continue  
            target = -nums[i]
            left, right = i + 1, n - 1
            while left < right:
                sum_ = nums[left] + nums[right]
                if sum_ == target:
                    res.append([nums[i], nums[left], nums[right]])
                    left += 1
                    while left < right and nums[left] == nums[left-1]:
                        left += 1
                    right -= 1
                    while left < right and nums[right] == nums[right+1]:
                        right -= 1
                elif sum_ < target: 
                    left += 1
                else:
                    right -= 1
        return res
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)  
        nums.sort()   
        res = []
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]:
                continue   
            target = -nums[i] 
            left, right = i+1, n-1
            while left < right:
                sum_ = nums[left] + nums[right] 
                if sum_ < target:
                    left += 1
                elif sum_ > target:
                    right -= 1
                else: 
                    res.append([nums[i], nums[left], nums[right]]) 
                    left += 1
                    while left < right and nums[left] == nums[left-1]:
                        left += 1
                    right -= 1
                    while left < right and nums[right] == nums[right+1]:
                        right -= 1
        return res    

18. 四數之和

  • 思路
    • example
    • 雙指針,三數之和推廣
    • 去重,三個層面: a, b, 以及c and d
  • 復雜度. 時間:O(n^3), 空間: O(1)
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        res  = []
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]: # 同層去重
                continue 
            for j in range(i+1, n):
                if j > i + 1 and nums[j] == nums[j-1]: # 同層去重
                    continue 
                target2 = target - (nums[i] + nums[j])
                left, right = j + 1, n - 1
                while left < right: 
                    sum_ = nums[left] + nums[right]
                    if sum_ == target2:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        left += 1
                        while left < right and nums[left] == nums[left-1]:
                            left += 1
                        right -= 1
                        while left < right and nums[right] == nums[right+1]:
                            right -= 1
                    elif sum_ < target2:
                        left += 1
                    else:
                        right -= 1
        return res 
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums) 
        res = []
        nums.sort()  
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]:
                continue  
            for j in range(i+1, n):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue  
                target2 = target-(nums[i] + nums[j]) # !!!
                left, right = j+1, n-1
                while left < right:
                    sum_ = nums[left] + nums[right] 
                    if sum_ < target2:
                        left += 1
                    elif sum_ > target2:
                        right -= 1
                    else:
                        res.append([nums[i], nums[j], nums[left], nums[right]]) 
                        left += 1
                        while left < right and nums[left] == nums[left-1]:
                            left += 1
                        right -= 1
                        while left < right and nums[right] == nums[right+1]:
                            right -= 1
        return res    
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容