摩尔投票法
核心思想:就是在不内斗的情况下对拼消耗,剩下的就是自己人
leetcode题目:多数元素
# 多数元素# 题解:通过投票法,一对一消耗,剩下的数,就是多少的元素了class Solution: def majorityElement(self, nums: List[int]) -> int: candidate = nums[0] # 初始化选择第一项 count = 1 # 初始化计数为1 for i in range(1, len(nums)): if count == 0: candidate = nums[i] # 如果计数器被清零,则重置candidate if candidate == nums[i]: # 如果新数字与candidate相等,则计数器加1 count += 1 else: # 否则计数器减1 count -= 1 return candidate
leetcode题目:只出现一次的数字
# 排序,然后循环判断间隔两两元素是否相等,不相等则可得到结果class Solution: def singleNumber(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] nums.sort() # 对数组进行排序 for i in range(1, len(nums), 2): # 因为排序后,相邻的两个数是相等的,所以可以两两判断,跳跃2位遍历 if nums[i-1] != nums[i]: return nums[i-1] # 如果单一元素是在列表的最后,则返回 if (i+2) == len(nums): return nums[-1]
# 依次删除列表的元素,同一个元素删除两次,报错则为目标值class Solution: def singleNumber(self, nums: List[int]) -> int: # 判断目标元素是否可以删除两次,报错即为目标值 while True: d = nums[0] nums.remove(d) try: nums.remove(d) except: return d
# 数组求和,与去重后的和相差的就是目标值class Solution: def singleNumber(self, nums: List[int]) -> int: # 数组去重后求和,减去原数组求和,即为目标值 return sum(set(nums))*2 - sum(nums)
from functools import reduce
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 位运算--异或
"""
异或:
1、a ^ a = 0
2、a ^ b ^ c = a ^ c ^ b
3、a ^ c ^ a = (a ^ a) ^ c = c
4、a ^ 0 = a
"""
return reduce(lambda x,y: x^y, nums)