Day6 Hash table
Hash function
Hash(ind) = x, i n d ∈ [ 0 , m − 1 ] ind \in [0,m-1] ind∈[0,m−1], x ∈ U x\in U x∈U
Hash table in Python
- Array: index and elements
- Set: unordered and non-duplicate
- Dictionary: key-value pairs
- map(): map(func, iter): iter is [] or {} etc.
Leetcode 242: Valid Anagram
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
counter1 = Counter()
for ss in s:
counter1[ss]+=1
counter2 = Counter()
for tt in t:
counter2[tt]+=1
if counter1 == counter2:
return True
else:
return False
Leetcode 349: Intersection of Two Arrays
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
nums1 = set(nums1)
nums2= set(nums2)
for num2 in nums2:
if num2 in nums1:
res.append(num2)
return res
Leetcode 202: Happy Number
def calculate_happy(num):
sum_ = sum([int(i)**2 for i in list(str(n))])
return sum_
record = set()
while True:
n = calculate_happy(n)
if n == 1:
return True
if n in record:
return False
else:
record.add(n)
Leetcode 1: Two sum
records = {}
for i, value in enumerate(nums):
if target - value in records:
return [records[target- value], i]
records[value] = i
return []