Majority Number
Description
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
It should support push, pop and min operation all in O(1) cost.
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
Example
Given [1, 1, 1, 1, 2, 2, 2], return 1
实现思路
这道题基于投票算法,
我们先假设数组nums中第一个数nums[0]就是我们要找的数vote,同时维护一个count变量,在后面判断中,如果nums[i] == vote(i=1….nums.length-1),则count++,如果不等,分两种情况:
1. 如果count > 0,则count–
2. 如果count = 0,则更新vote = nums[i]
为什么这样能得到我们要求的数major?我们可以这样分析:
对于任意一个数组nums中不等于major的数,基于我们的算法,它最终一定会被替换。因为它们的count(不超过一半)必定会在major(count大于一半)的不等判断下,被替换
那major会不会被替换呢?可能中间过程会,但遍历到最后,留下的必定是major。
根据此思路,求解方法如下:
java实现
public class Solution {
/** * @param nums: a list of integers * @return: find a majority number */
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
int vote = nums.get(0);
int count = 1;
for(int i = 1 ; i < nums.size(); i ++){
if(nums.get(i) == vote){
count ++;
}else if(count == 0){
vote = nums.get(i);
}else{
count --;
}
}
return vote;
}
}
python实现
class Solution:
""" @param nums: A list of integers @return: The majority number """
def majorityNumber(self, nums):
# write your code here
if not nums:
return None
vote = nums[0]
count = 0
for num in nums:
if num == vote:
count += 1
elif count == 0:
vote = num
else:
count -= 1
return vote