版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/83280572
数组中出现次数超过一半的数字 java
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
代码1:
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
int count = 0;
int temp = 0;
if(array.length <= 0 || array == null){
return 0;
}
if(array.length == 1){
return array[0];
}
for(int i = 0; i < array.length - 1; i++){
if(array[i] == array[i+1]){
temp = array[i];
count++;
}
}
if(count >= array.length / 2){
return temp;
}
return count;
}
}
代码2: