Majority Number
题目:
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
分析:
因为majority number超过数组的一半,所以用这种greedy方法有效。
解法:
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
int count = 0;
int res = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
if (count == 0) {
res = nums[i];
count++;
} else{
if (res == nums[i]) {
count++;
} else {
count--;
}
}
}
return res;
}
};