通过数组创建
hashTable = [’ ']*4
通过字典创建
mapping = {}
添加元素
时间复杂度O(1)
hashTable[1] = ‘han’
hashTable[2] = ‘han’
hanhTable[3] = ‘han’
mapping[1] = ‘han’
mapping[2] = ‘han’
mapping[3] = ‘han’
更新元素
时间复杂度O(1)
hashTable[1] = ‘aaa’
mapping[1] = ‘bbb’
移除元素
时间复杂度O(1)
hashTable[1] = ’ ’
mapping.pop(1)
获取值
时间复杂度O(1)
hashTable[3]
mapping[3]
校验
3 in mapping
长度
len(mapping)
len(mapping) == 0
力扣题
- 存在重复元素
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
class Solution:
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
- 找不同
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
class Solution:
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'
- 下一个更大元素
nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res =[]
stack = []
for num in nums2:
stack.append(num)
for num in nums1:
temp = []
isFound = False
nextMax = -1
while (len(stack) != 0 and not isFound):
top = stack.pop()
if top > num:
netMax = top
elif top == num:
isFound = True
temp.append(top)
res.append(nextMax)
while len(temp) != 0 :
stack.append(temp.pop())
return res
版权声明:本文为qq_51924093原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。