package test002;
public class Main {
public static void main(String[] args) {
int[] array={1,2,3,3,3,3,5,4,2};
int num=MoreThanHalfNum_Solution(array);
System.out.println(num);
}
public static int MoreThanHalfNum_Solution(int[] array) {
int result=array[0];
int len=array.length;
int times=1;
<span style="white-space:pre"> </span>//获得数组中有可能是出现次数超过一半的数,我们要找的数字出现的次数比他所有数字出现的次数之和还要多
for(int i=1;i<len;i++){
<span style="white-space:pre"> </span>//如果times==则换另外一个数
if(times==0){
result=array[i];
times++;
}else if(result==array[i]){
times++;
}else{
times--;
}
}
if(!checkIs(array,result)){
result=0;
}
return result;
}
<span style="white-space:pre"> </span>//判断所找出来的数是否是真正的超过一班的数
private static boolean checkIs(int[] array, int result) {
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]==result){
count++;
}
}
return count>array.length/2?true:false;
}
}
题目描述
package test002;
public class Main {
public static void main(String[] args) {
int[] array={1,2,3,3,3,3,5,4,2};
int num=MoreThanHalfNum_Solution(array);
System.out.println(num);
}
public static int MoreThanHalfNum_Solution(int[] array) {
int result=array[0];
int len=array.length;
int times=1;
<span style="white-space:pre"> </span>//获得数组中有可能是出现次数超过一半的数,我们要找的数字出现的次数比他所有数字出现的次数之和还要多
for(int i=1;i<len;i++){
<span style="white-space:pre"> </span>//如果times==则换另外一个数
if(times==0){
result=array[i];
times++;
}else if(result==array[i]){
times++;
}else{
times--;
}
}
if(!checkIs(array,result)){
result=0;
}
return result;
}
<span style="white-space:pre"> </span>//判断所找出来的数是否是真正的超过一班的数
private static boolean checkIs(int[] array, int result) {
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]==result){
count++;
}
}
return count>array.length/2?true:false;
}
}
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。