class Solution:
# 136. 只出现一次的数字
'''给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。'''
def containsDuplicate(self, nums):
dic = {}
for i in nums:
if i in dic:
return True
else:
dic[i] = 1
return False
# 借助字典
# 169. 多数元素
'''给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。'''
def majorityElement(self, nums):
count, majorE = 0, 0
for num in nums:
if count == 0:
majorE = num
count += (1 if num == majorE else -1)
return majorE
#如果我们把众数记为+1,把其他数记为−1,将它们全部加起来,显然和大于 0,从结果本身我们可以看出众数比其他数多。
# 15. 三数之和
'''给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。'''
def threeSum(self, nums):
n = len(nums)
nums.sort()
ans = list()
# 枚举 a
for first in range(n):
# 需要和上一次枚举的数不相同
if first > 0 and nums[first] == nums[first - 1]:
continue
# c 对应的指针初始指向数组的最右端
third = n - 1
target = -nums[first]
# 枚举 b
for second in range(first + 1, n):
# 需要和上一次枚举的数不相同
if second > first + 1 and nums[second] == nums[second - 1]:
continue
# 需要保证 b 的指针在 c 的指针的左侧
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加
# 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans
if __name__ == "__main__":
s = Solution()
# arr = [1,2,3,1]
# print(s.containsDuplicate(arr))
arr = [2,2,1,3,5,6,2]
print(s.majorityElement(arr))
# arr = [-1,0,1,2,-1,-4]
# print(s.threeSum(arr))
数据结构刷题 第一天
最新推荐文章于 2024-06-15 13:40:50 发布