169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
找一个数,出现次数大于数字长度的一半。on做法维护一个majority数和他当前遇到相同数的个数,如果下一个数相同,计数+1,否则计数-1,计数=0的时候换majority,因为要找的数长度一定大于数组的一半,因此最后剩下来的数一定是majority
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ majority = nums[0] count = 1 for i in range(1, len(nums), 1): if nums[i] == majority: count += 1 else: count -= 1 if count == 0: majority = nums[i] count = 1 return majority