public static int moreHalfSimple(int[] num) { int count =1; int index; int result=num[0]; for(index = 1;index<num.length-1;index++) { if(count==0) { result = num[index]; count=1; } if(result != num[index]) count--; else count++; } if(!checkHalf(num,result)) { result=-1;//没找到返回-1 } return result; } //判断数字是否出现了数组一半以上的长度 private static boolean checkHalf(int[] num, int result) { int count=0; for(int i =0;i<num.length;i++) { if(num[i] == result) count++; } if(count*2 <=num.length) return false; return true; }
private static int partition(int []num,int start,int end) { if(num==null || num.length ==0) return -1; int s = num[end]; int minIndex=start-1; int maxIndex=start; for(;maxIndex<end;maxIndex++) { if(num[maxIndex] <= num[end]) { minIndex++; swap(num,minIndex,maxIndex); } } swap(num,minIndex+1,maxIndex); return minIndex+1; } private static void swap(int[] num ,int a ,int b) { int temp = num[a]; num[a] = num[b]; num[b] = temp; } static boolean inputflag= false;//全局变量记录是输入无效还是没找到 public static int moreThanhalf(int[] num,int start,int end) { if(num ==null || num.length==0 ||start>end) { inputflag=true; return -1; inputflag为true且返回-1,说明输入无效 } int result=0; int middle = num.length >> 1; int index; index = partition(num, start, end); while(index != middle) { if(index>middle) { index =partition(num, start, index-1); } else { index = partition(num, index+1, end); } } result = num[middle]; if(!checkHalf(num,result)) { result =0;//返回0且inputFlag为false说明没找到 } return result; } private static boolean checkHalf(int[] num, int result) { int count=0; for(int i =0;i<num.length;i++) { if(num[i] == result) count++; } if(count*2 <=num.length) { inputflag=false; return false; } return true; }
版权声明:本文为博主原创文章,转载请注明出处。
原文地址:http://blog.csdn.net/u014307117/article/details/47442437