package com.google.android;
public class FindBeyondHalfID {
public static void main(String[] args) throws Exception {
int[] data = { 1, 2, 2, 3, 4, 5, 2, 2, 2 };
int result = find(data);
System.out.println(result);
}
/**
* 查出数组中出现次数超过一半的数
* @param data
* @return
* @throws Exception
*/
private static int find(int[] data) throws Exception {
if (data != null && data.length > 0) {
int result = data[0];
int times = 1;
for (int i = 0; i < data.length; i++) {
if (times == 0) {
result = data[i];
times = 1;
} else if (data[i] == result) {
times++;
} else {
times--;
}
}
return result;
} else {
throw new Exception("data is null");
}
}
}
数组中出现次数超过一半的数
最新推荐文章于 2022-04-18 17:35:57 发布