代码随想训练营第五天(Python)| 242.有效的字母异位词、349. 两个数组的交集、第202题. 快乐数、 1. 两数之和

发布时间 2023-10-16 23:52:03作者: 忆象峰飞

242.有效的字母异位词

1、数组法

这个思路贼 6 ,在这个题的效率也高

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # 全部转为 asii 码 如果是互为异为词,则最后的 -+ 后的结果为 0
        record = [0] * 26  # 范围是 26。一维
        for i in s:
            record[ord(i)-ord("a")] += 1
        for j in t:
            record[ord(j)-ord("a")] -= 1
        for i in range(26):
            if record[i] != 0:
                return False
        return True
2、字典法
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s_dict = {}
        for i in s:
            s_dict[i] = s_dict.get(i, 0) + 1
        for j in t:
            s_dict[j] = s_dict.get(j, 0) - 1
        for j in s_dict.values():
            if j != 0:
                return False
        return True

349. 两个数组的交集

1、集合

list 很大时适合用这个或者哈希表,不能使用下面数组方法

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        a_set = set()
        for i in nums1:
            a_set.add(i)
        for j in nums2:
            if j in a_set:
                a_set.remove(j)
                res.append(j)
        return res
2、数组

这个思路很不错

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count1 = [0] * 1001  # 力扣范围为 1000,这里可看成二维数组
        count2 = [0] * 1001
        res = []
        for i in range(len(nums1)):
            count1[nums1[i]] += 1
        for j in range(len(nums2)):
            count2[nums2[j]] += 1
        for k in range(1001):
            if count1[k] * count2[k] > 0:
                res.append(k)
        return res

三、第202题. 快乐数

关键点:出现同样要计算的数字时,就会陷入无限循环,就不是快乐数了

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n != 1:
            n_nums = [int(i)**2 for i in str(n)]
            n = sum(n_nums)
            if n in seen:
                return False
            seen.add(n)
        return True

四、1.两数之和

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        a_dict = {}
        for index, val in enumerate(nums):
            target_val = target - val
            if target_val in a_dict:
                return [index, a_dict.get(target_val)]
            a_dict[val] = index
        return []