数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
方法1:根据位置判断
将数组按照顺序排序后,超过数组长度一半的数字一定是排序后中间的那个数字
首先找到位于中间的数字,然后判断它的个数判断是否合法
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length==0)
return 0;
int start=0,end=array.length-1;
int mid=array.length/2;
int index=partition(array,start,end);
while(index!=mid){ //找到中间的位置的数据,array[index]
if(index>mid){
end=index-1;
index=partition(array,start,end);
}else{
start=index+1;
index=partition(array,start,end);
}
}
int index_count=count(array,index);
return index_count>array.length/2?array[index]:0;
}
public int partition(int[] array,int low,int high){ //快排,partition
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;
}
public int count(int[] array,int index){ //统计index位置个数
int index_count=0;
for(int i=0;i<array.length;i++){
if(array[i]==array[index])
index_count++;
}
return index_count;
}
}
或者
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length==0)
return 0;
Arrays.sort(array);
return count(array,array[array.length/2])>array.length/2?array[array.length/2]:0;
}
public int count(int[] array,int result){ //统计index位置个数
int index_count=0;
for(int i=0;i<array.length;i++){
if(array[i]==result)
index_count++;
}
return index_count;
}
}
方法2:根据个数判断
因为数字在数组中出现次数的超过一半,遍历数组,保存两个值:一个是数组中的一个数字,另一个是次数
当遍历到下一个数字的时候,如果下一个数字和之前保存的数字相同,则次数加一;如果下一个数字和我们之前保存的数字不同,则次数减一。如果次数为0,那么我们需要保存下一个数字,并把次数设为一
最终,要找的数字肯定是最后一次次数设为1对应的数字
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length==0)
return 0;
int result=array[0];
int times=1;
for(int i=1;i<array.length;i++){
if(times==0){
result=array[i];
times=1;
}else if(result==array[i]){
times++;
}else{
times--;
}
}
return count(array,result)>array.length/2?result:0;
}
public int count(int[] array,int result){ //统计index位置个数
int index_count=0;
for(int i=0;i<array.length;i++){
if(array[i]==result)
index_count++;
}
return index_count;
}
}