class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
if(numbers.empty())
return 0;
int count =0;
int midVal =0;
int tobesorted =0;
//排序算法
int i=0,j=0;
for (i = 1; i < numbers.size(); ++i)
{
j = i;
tobesorted = numbers[i];
while (j > 0 && tobesorted < numbers[j - 1])
{
numbers[j] = numbers[j - 1];
//由于前面的数组已经是排好序的,那么只需要找到第一个低于当前值,放于其前面就好了
j--;
}
numbers[j] = tobesorted;
}
midVal = numbers[numbers.size()/2];
for(int i=0; i<numbers.size(); ++i)
{
if(midVal == numbers[i])
++count;
}
if(2*count > numbers.size())
return midVal;
else
return 0;
}
};
原文:http://www.cnblogs.com/shewell/p/6492704.html