哈希表基础题217. 存在重复元素、389. 找不同、496. 下一个更大元素 I

发布时间 2023-08-28 13:26:49作者: 小吴要努力
217. 存在重复元素
 1 class Solution:
 2     def containsDuplicate(self, nums: List[int]) -> bool:
 3         #方法1:set去重,直接比较去重之后数组长度
 4         if len(set(nums)) != len(nums):
 5             return True
 6         else:
 7             return False
 8 
 9         # 方法2:哈希表(字典)
10         numset = {}
11         for i in nums:
12             if i not in numset:
13                 numset [i] = 1
14             else :
15                 return True
16         return False
17         
18         #方法3:排序+判断相邻元素是否重复
19         nums.sort()
20         for i in range(len(nums)-1):
21             if nums[i] == nums[i+1]:
22                 return True
23         return False

389. 找不同

 1 class Solution:
 2     def findTheDifference(self, s: str, t: str) -> str:
 3         #方法1
 4         for i in t:
 5             if t.count(i) - s.count(i) == 1:
 6                 return i
 7         
 8         #方法2:哈希表
 9         hasmap = {}
10 
11         for str in s+t:
12             if str not in hasmap:
13                 hasmap[str] = 1
14             else:
15                 hasmap[str] += 1
16 
17         for str in hasmap:
18             if hasmap[str] % 2 != 0:
19                 return str

496. 下一个更大元素 I

 1 class Solution:
 2     def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
 3         #单调栈+(哈希映射)
 4         result = [-1] * len(nums1)
 5         stack = [0] #存放数组2的0号下标
 6         for i in range(1,len(nums2)):
 7             if nums2[i] <= nums2[stack[-1]]:
 8                 stack.append(i)
 9             else:
10                 #栈不为空再弹出元素 #s是一个持续的过程
11                 while len(stack) != 0 and nums2[i] > nums2[stack[-1]]:
12                     if nums2[stack[-1]] in nums1:
13                         #找出对应值在数组1中的下标
14                         index = nums1.index(nums2[stack[-1]])
15                         result[index] = nums2[i]
16                     stack.pop()
17                 stack.append(i) #找到符合条件的值之后,再将当前元素加入栈中
18         
19         return result