Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
Example
Example1:
Given [1, 1, 1, 1, 2, 2, 2], return 1
Example2:
Given [1, 1, 1, 2, 2, 2, 2], return 2
Challenge
O(n) time and O(1) extra space
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majorityNumber(self, nums):
# write your code here
nums.sort()
return nums[len(nums)//2]
超过了1/2,所以最中间的元素肯定是决定最多元素
[Lintcode]46. Majority Element/[Leetcode]169. Majority Element
原文:https://www.cnblogs.com/siriusli/p/10359939.html