""" 多数元素 """ from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: """ 多数元素 :param nums: :return: """ count = 0 candidate = None for i in nums: if count == 0: candidate = i if i == candidate: count += 1 else: count += -1 return candidate def majorityElement2(self, nums: List[int]) -> int: """ 多数元素 :param nums: :return: """ count = 0 candidate = None for i in nums: if count == 0: candidate = i count += (1 if i == candidate else -1) return candidate if __name__ == '__main__': root = Solution().majorityElement2([3, 2, 3]) print(root)