class Solution(object):
def isAnagram(self, s, t):
if len(s) != len(t):
return False
freq = [0] * 26
for i in range(len(s)):
freq[ord(s[i]) - ord('a')] += 1
freq[ord(t[i]) - ord('a')] -= 1
for i in range(len(freq)):
if freq[i] != 0:
return False
return True
时间复杂度:O(n)
空间复杂度:O(n)
349 两个数组的交集
class Solution(object):
def intersection(self, nums1, nums2):
ans = set()
for num in nums1:
if num in nums2:
ans.add(num)
return ans
时间复杂度:O(n)
空间复杂度:O(n)
202 快乐数
class Solution(object):
def isHappy(self, n):
mem = set()
while n != 1:
n = sum([int(i)**2 for i in str(n)])
if n in mem:
return False
else:
mem.add(n)
else:
return True
时间复杂度:O(n)
空间复杂度:O(n)
1 两数之和
class Solution:
def twoSum(self, nums, target) ->
seen = set()
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [nums.index(complement), i]
seen.add(num)