复杂度:O(n)不改变数组原先顺序
#include
using namespace std;
void findMoreThanHalfEle(int arr[],int length)
{
if(NULL== arr ||length <= 0)
{
cout<<“input error”<<endl;
return ;
}
int res = arr[0];
int count = 1 ;
for(int i = 1 ; i<length ; i++)
{
if(res == arr[i])
{
count++;
}
else
{
count--;
if(0 == count)
{
res = arr[i];
count = 1;
}
}
}
cout<<"The element is:"<<res<<endl;
}
int main()
{
int n ;
int arr[2005]={0};
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
}
findMoreThanHalfEle(arr,n);
return 0;
}
复杂度:O(n)改变数组原有顺序,快排思想