题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
思路:利用数组本身的特性,如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
代码:
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int length=array.length;
if(array==null||length<=0){
return 0;
}
int result=array[0];
int times=1;
for(int i=1;i<length;i++){
if(times==0){
result=array[i];
times=1;
}else{
if(array[i]==result){
times++;
}else{
times--;
}
}
}
times=0;
for(int i=0;i<length;i++){
if(result==array[i]){
times++;
}
}
if(times>length/2){
return result;
}else{
return 0;
}
}
}
第二种想法,利用快速排序的过程
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length==0) return 0;
int low = 0;
int high = array.length-1;
int mid = (low+high)/2;
int index = partition(array, 0, high);
while(index!=mid){
if(index<mid){
index = partition(array, index+1, high);
}else{
index = partition(array, low, index-1);
}
}
int count = 0;
for(int i=0;i<=high;i++){
if(array[i]==array[mid]) count++;
}
if(count<=(high+1)/2){
return 0;
}
return array[mid];
}
public int partition(int [] array,int low,int high){
int temp = array[low];
while(low<high){
while(low<high && array[high]>=temp){
high--;
}
array[low] = array[high];
while(low<high && array[low]<=temp){
low++;
}
array[high] = array[low];
}
array[low] = temp;
return low;
}
}