数组中出现次数超过一半的数字
1.
2.
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array==null||array.length==0){
return -1;
}
int start=0;
int end=array.length-1;
int index=partition(array,start,end);
while(index<array.length/2){
start=index+1;
index=partition(array,start,end);
}
int result = array[array.length/2];
int times = 0;
for(int i=0;i<array.length;++i){
if(array[i] == result)
times++;
}
if(times*2<=array.length){
return 0;
}else{
return result;
}
}
public int partition(int[] a,int low,int high) {
int pivot = a[low];
while (low < high) {
while (low < high && a[high] >= pivot) {
--high;
}
a[low]=a[high];
while (low < high && a[low] <= pivot) {
++low;
}
a[high]=a[low];
}
a[low]=pivot;
return low;
}
}