-
- 题目描述
- 链接地址
- 解法
- 算法解释
题目描述
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
.
链接地址
http://www.lintcode.com/en/problem/majority-number-ii/
解法
int majorityNumber(vector<int> nums){
// write your code here
int num1 = 0, num2 = 0;
int ret1 = 0, ret2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (num1 != 0 && ret1 == nums[i]) {
num1++;
} else if (num2 != 0 && ret2 == nums[i]) {
num2++;
} else if (num1 != 0 && num2 != 0) {
num1--;
num2--;
} else if (num1 == 0) {
num1 = 1;
ret1 = nums[i];
} else {
num2 = 1;
ret2 = nums[i];
}
}
int count1 = 0, count2 = 0;
for (int i = 0; i < nums.size(); i++) {
if (ret1 == nums[i]) {
count1++;
} else if (ret2 == nums[i]) {
count2++;
}
}
if (count1 > count2) {
return ret1;
} else {
return ret2;
}
}
算法解释
正如算法Majority Number,同时删除两个元素,现在同时删除三个元素。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-28 21:13:36