题目:majorityNumber
要求:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
样例:
给出数组[1,1,1,1,2,2,2],返回 1
算法要求:
要求时间复杂度为O(n),空间复杂度为O(1)
解题思路:
每次假设n为主元素,每次将主元素与别的元素进行比较,如果相同也count++, 如果不同则count–,
相当于将不相同的元素和主元素二个元素删除了。如果主元素减为了0, 则将当前的数假设为主元素,再继续遍历。
最后跳出循环,count!=0的时候,n就代表主元素的下标。
算法如下:
int majorityNumber(vector<int> nums) {
// write your code here
int size = nums.size();
int n = 0;
int count = 1;
for (int i = 1; i < size; i++) {
if (nums[n] != nums[i]) {
count--;
} else {
count++;
}
if (count == 0) {
count = 1;
n = i;
}
}
return nums[n];
}