public class E39MoreThanHalfNum {
//数组中出现次数超过一半的数字
public static int getNumber(int[] numbers, int length){
if (numbers == null || length <= 0)
throw new IllegalArgumentException("Invalid Parameters!");
int result = numbers[0];
int times = 1;
for (int i = 1; i < length; i ++){
if (times == 0){
result = numbers[i];
times = 1;
}
else if (result == numbers[i])
times ++;
else
times --;
}
if (!isMoreThanHalf(numbers, result)){
System.out.println("No target!");
return -1;
}
return result;
}
private static boolean isMoreThanHalf(int[] numbers, int number){
int count = 0;
for(int anumber : numbers){
if (anumber == number)
count ++;
}
return count > (numbers.length / 2);
}
//测试用例
public static void main(String[] args){
int[] numbers1 = {1, 2, 2, 2, 3};
int[] numbers2 = {1, 2, 2, 2, 3, 4, 5, 6, 7};
System.out.println(E39MoreThanHalfNum.getNumber(numbers1, 5));
System.out.println(E39MoreThanHalfNum.getNumber(numbers2, 9));
}
}
数组中出现超过一半的数字(Java实现)
最新推荐文章于 2020-05-03 17:51:40 发布