import java.util.ArrayList;
public class OccurenceMoreThanOneHalf {
public static void main(String[] args) {
int a[]={1,2,2,2,2,3,5,4,2,2};
getoccurencymorethanonehalf(a);
}
//判断数组中是否存在出现次数超过长度1半的元素
public static boolean checkmorethanonehalf(int a[],int b){
int count=0;
for(int i=0;i<a.length;i++){
if(a[i]==b){
count++;
}
}
if(count*2>a.length){
return true;
}else{
return false;
}
}
public static void getoccurencymorethanonehalf(int [] a){
if(a.length==0){
return;
}else{
ArrayList<Integer> a1=new ArrayList<Integer>();
int index=1;
int temp=a[0];
a1.add(temp);
for(int i=1;i<a.length;i++){
if(a[i]!=temp){
index--;
if(index==0){
temp=a[i];
index=1;
a1.add(temp);
}
}else{
index++;
}
}
int result=a1.get(a1.size()-1);
if(checkmorethanonehalf(a, result)){
System.out.println(result);
}else{
System.out.println("输入不符合要求");
}
}
}
public static void exch(int a[],int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static int partition(int a[],int start,int end){
int basevalue=a[start];
int basepos=start;
for(int i=start+1;i<=end;i++){
if(a[i]<basevalue){
exch(a, i, basepos);
}
}
exch(a, start, basepos);
return basepos;
}
public static void getoccurencymorethanonehalf2(int a[]){
int mid=a.length/2;
int start=0;
int end=a.length-1;
int pos=partition(a, start, end);
while(pos!=mid){
if(pos< mid){
start=pos+1;
pos=partition(a, start, end);
}else{
end=pos-1;
pos=partition(a, start, end);
}
}
if(checkmorethanonehalf(a, a[pos])){
System.out.println(a[pos]);
}else{
System.out.println("输入数组不符合要求");
}
//return a[pos];
}
}