Day6 Hash table: hash mapping

Hash function

Hash(ind) = x, i n d ∈ [ 0 , m − 1 ] ind \in [0,m-1] ind[0,m1], x ∈ U x\in U xU

Hash table in Python

  1. Array: index and elements
  2. Set: unordered and non-duplicate
  3. Dictionary: key-value pairs
  4. 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 []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值