您的位置:首页 > 职场人生

剑指offer面试题29:数组中出现次数超过一半的数字

2016-09-20 23:36 531 查看
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

思路:参考任意第K大数字,排序后,数组中位的数一定是出现次数超过一般的数。O(n(1+1/2+….+1/2k))=O(n)。

#include <iostream>
#include <vector>

using namespace std;

int Partition(vector<int> &num, int length, int begin, int end) {
if (num.empty() || length <= 0 || begin < 0 || end >= length)
return -1;
int index = begin;
int small = begin - 1;
while (index < end) {
if (num[index] < num[end]) {
++small;
int temp = num[index];
num[index] = num[small];
num[small] = temp;
}
++index;
}
++small;
int temp = num[small];
num[small] = num[end];
num[end] = temp;
return small;
}

int MoreThanHalf(vector<int> num, int length) {
if (num.empty() || length <= 0)
return -1;
int middle = length >> 1;
int begin = 0;
int end = length - 1;
int index = Partition(num, length, begin, end);
while (index != middle) {
if (index > middle) {
end = index - 1;
index = Partition(num, length, begin, end);
} else {
begin = index + 1;
index = Partition(num, length, begin, end);
}
}
int result = num[middle];
int times = 0;
for (int i = 0; i < length; i
4000
++) {
if (result == num[i])
++times;
}
if (length >= times * 2)
result = -1;
return result;
}

int main() {
vector<int> num;
int a;
while (cin >> a) {
num.push_back(a);
}
a = num.size();
int result = MoreThanHalf(num, a);
cout << result << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: