【哈希表】哈希, ord(), any(iterable); 判断是否重复用set; 用Map存储 | 刷题第6天 | 242.有效的字母异位词; 349. 两个数组的交集; 202. 快乐数; 1. 两数之和

哈希, ord(), any(iterable)

Problem: 242. 有效的字母异位词

思路

讲述看到这一题的思路

要快速判断一个元素是否出现集合里的时候,就要考虑哈希法

解题方法

描述你的解题方法

关键点1: Python要用ord()函数来把字符转为整数

关键点2: Python可以使用any(iterable)来对iterable类型进行判断是否为null/0/false

    for element in iterable:
        if element:
            return True
    return False

复杂度

  • 时间复杂度:

添加时间复杂度, 示例: $O(n)$

应该是$O(n)$

  • 空间复杂度:

添加空间复杂度, 示例: $O(n)$

应该是$O(1)$

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        h = [0] * 26
        for ch in s:
            h[ord(ch) - ord('a')] += 1
        for ch in t:
            h[ord(ch) - ord('a')] -= 1
        return not any(h)

Problem: 349. 两个数组的交集

思路

讲述看到这一题的思路

笑死, 代码风格C里C气的

Code

看到一份很Python的代码

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

我的代码就C里C气的

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        h = [0] * 1005
        s = set([])
        for i in nums1:
            if h[i] == 0:
                h[i] = 1
        for i in nums2:
            if h[i] == 1:
                s.add(i)
        return list(s)            

判断是否重复用set

Problem: 202. 快乐数

思路

讲述看到这一题的思路

关键点1: 可以用反证法证明: 若为快乐数, 一定不存在循环(循环条件为不等于1)

关键点2: (题目给的结论, 还不知道怎么证明)若不是快乐数, 一定存在循环 => 用set

Code


class Solution:
    def isHappy(self, n: int) -> bool:
        # 举例: 2: 4, 16, 1+36=37, 9+49=59, 25+81=106, 1+36=37, ...
        # 证明: 若为快乐数, 一定不存在循环(循环条件为不等于1)

        s = set([]) # 用set记录

        # 计算过程
        sum = 0
        while sum != 1:
            sum = 0
            while n > 0:
                x = n % 10
                n = int(n / 10)
                sum += x*x
            n = sum
            if n not in s: 
                s.add(n)
            else: # 若set中重复
                return False
        return True

【重点】用Map存储

Problem: 1. 两数之和

思路

讲述看到这一题的思路

最简单的想法: 暴力求解/枚举

另一想法: 用Map存储, 时间$O(n)$, 空间$O(n)$

Code

暴力解法:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 最简单的想法: 暴力求解/枚举
        for i in range(len(nums)-1):
            j = i + 1
            while j < len(nums):
                if nums[i] + nums[j] == target:
                    return [i,j]
                j += 1

用map

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 如何用O(n) => 用一个map,存储已经遍历的值
        m = {}
        for idx,val in enumerate(nums):
            if target - val not in m:
                m[val] = idx
            else:    
                return list([idx, m[target - val]])
posted @ 2022-10-31 19:07  ywh-pku  阅读(37)  评论(0)    收藏  举报