242.有效的字母异位词
字符串仅包含小写字母,那么可以使用数组声明26位大小,遍历其中一个字符串,记录字符的个数,然后遍历另一个字符串,减去相应字符,最后都为0则符合条件
class Solution:def isAnagram(self, s: str, t: str) -> bool:record = [0] * 26for ch in s:record[ord(ch) - ord('a')] += 1for ch in t:if record[ord(ch) - ord('a')] <= 0:return Falserecord[ord(ch) - ord('a')] -= 1for num in record:if num != 0:return Falsereturn True
349. 两个数组的交集
如果没有限制范围的话,使用下面的方式即可。限制小范围后可以声明范围大小的数组,先遍历其中一个数组,有该数值的置为1,然后遍历另一个数组,此时可以记录两个数组都有的元素
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:return list(set(nums1).intersection(set(nums2)))
202. 快乐数
本题的重点在于不能变为1的会进入无限循环,所以可以使用set将中间所有数据都保存起来,一旦遇到重复数据则说明进入了无限循环,不是快乐数
class Solution:def isHappy(self, n: int) -> bool:if n == 1:return Truerecord = set()while n != 1:if n in record:return Falserecord.add(n)n = self.get_num(n)return Truedef get_num(self, n):res = 0while n != 0:res += (n % 10) ** 2n //= 10return res
1. 两数之和
可以使用暴力求解,双重循环
使用哈希法求解,key为元素值,value为索引值,注意:数组中有重复元素,但是题目已经假设每种输入只会对应一个答案,因此不会有影响
class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:num_dict = {}for index, num in enumerate(nums):if target - num in num_dict:return [num_dict[target-num], index]num_dict[num] = indexreturn []