只需将当前元素与前一个元素进行比较,计算连续元素的数量,如果检测到连续元素,则检查它是否大于现有最大值并跟踪该值:
public static int findMostConsecutive(int ... arr) {
int res = arr[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
count++;
if (count > maxCount) {
maxCount = count;
res = arr[i];
}
}
else {
count = 1;
}
}
return res;
}
测试:
System.out.println("Most consecutive: " + findMostConsecutive(1, 2, 1, 1, 3, 3, 3, 4, 2));
System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3));
System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3, 3, 3));
输出
Most consecutive: 3
Most consecutive: 2
Most consecutive: 3