标签:eth mes 试题 efi lock rap return 超过 数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include "ListNode.h"
#include "TreeNode.h"
#include "Graph.h"
using namespace std;
#define MAXNUM 100010
#define DRIFT 1001
void mySwap(vector<int> &num, int i, int j){
int temp = num[j];
num[j] = num[i];
num[i] = temp;
}
int myPartition(vector<int> &num, int low, int high){
int pivot = num[low];
while(low < high){
// 将右边比pivot小的放到左边
while(low < high && num[high] >= pivot)
high--;
mySwap(num, low, high);
while(low < high && num[low] <= pivot)
low++;
mySwap(num, low, high);
}
return low;
}
// 快排
void QSort(vector<int> &num, int low, int high){
if(low >= high)
return ;
int pivot = myPartition(num, low, high);
QSort(num, low, pivot - 1);
QSort(num, pivot + 1, high);
}
// 已排序的数组
int MoreThanHalfNum_Solution(vector<int> numbers) {
// 先排序
QSort(numbers, 0, numbers.size() - 1);
for(int i = 0; i < numbers.size(); i++)
cout<<numbers[i];
cout<<endl;
// 数组的一半
int halfNum = numbers.size() / 2;
for(int i = 0; i <= halfNum; i++){
int sum = 0;
for(; sum < halfNum + 1; sum++)
if(numbers[i + sum] != numbers[i])
break;
if(sum == halfNum + 1){
return numbers[i];
break;
}
}
return 0;
}
int main()
{
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(5);
numbers.push_back(4);
numbers.push_back(2);
cout<<MoreThanHalfNum_Solution(numbers);
return 0;
}
标签:eth mes 试题 efi lock rap return 超过 数字
原文地址:https://www.cnblogs.com/flyingrun/p/13525318.html