【手把手带你刷Leetcode力扣】6.数据结构 - 哈希表

哈希表:

散列表
key : value

  • 数组实现
  • java - hashmap
  • python - 字典

key -> 哈希函数 -> 内存地址 -> key/value对应的内存地址

  • 哈希碰撞:2个不同的key通过同一个哈希函数得到相同的内存地址

链表解决哈希碰撞


时间复杂度

  • 访问Access — X
  • 搜索Search — O(1) — 碰撞情况 — O(k) — k为碰撞元素的个数
  • 插入Insert — O(1)
  • 删除Delete — O(1) — 碰撞情况

常用操作

  1. 创建哈希表
    hashTable = [ ’ ’ ]*4

    mapping = { }

  2. 添加元素
    学号:姓名
    O(1)

    hashTable[1] = ‘hanmeimei’
    hashTable[2] = ‘lihua’
    hashTable[3] = ‘siyangyuan’

    mapping[1] = ‘hanmeimei’
    mapping[2] = ‘lihua’
    mapping[3] = ‘siyangyuan’

  3. 删除元素
    hashTable[1] = ’ ’

    mapping.pop(1)
    (key)

    del mapping[1]

  4. 修改元素
    hashTable[1] = ‘bishi’

    mapping[1] = ‘bishi’
    O(1)

  5. 获取key的value
    hashTable[3]

    mapping[3]
    O(1)

  6. 检测key是否存在
    3 in mapping
    O(1)

  7. 哈希表长度以及哈希表是否还有元素
    len(mapping) == 0
    O(1)


练习题

  • 217 . 存在重复元素
class Solution:
	# Hash map
	# Time complexity: O(N)
	# Space complexity: O(N)
	def containsDuplicate(self, nums: List[int]) -> bool:
		if len(nums) == 0:
			return False
		mapping = {}
		for num in nums:
			if num not in mapping:
				mapping[num] = 1
			else:
				mapping[num] = mapping.get(num) + 1
		for v in mapping.values():
			if v > 1:
				return True
		return False
  • 389 . 找不同
class Solution:
	# Hash Table
	# N is the size of t
	# Time complexity: O(N)
	# Space complexity: O(N)
	def findTheDifference(self, s: str, t: str) -> str:
		if len(s) == 0:
			return t
		table = [0]*26
		for i in range(len(t)):
			if i < len(s):
				table[ord(s[i])-ord('a')] -= 1
			table[ord(t[i]-ord('a')] += 1
		for i in range(26):
			if table[i] != 0:
				return chr(i+97)
		return 'a'
  • 496 . 下一个更大元素
class Solution:
	# Stack
	# M is the size of nums1, N is the size of nums2
	# Time Complexity: O(M+N)
	# Space Complexity: O(N)
	def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
		res = []
		stack = []
		mapping = {}
		for num in nums2:
			while len(stack) != 0 and num > stack[-1]:
				temp = stack.pop()
				mapping[temp] = num
			stack.append(num)
			
		while len(stack) != 0:
			mapping[stack.pop()] = -1
			
		for num in nums1:
			res.append(mapping[num])
			
		return res

学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值