You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
548 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package 02.mca_01;
// 找到数组中的水王数
// 本题来自大厂刷题班23节
public class Problem01_WaterKing {
public static int waterKing(int[] arr) {
int cand = 0;
int hp = 0;
for (int i = 0; i < arr.length; i++) {
if (hp == 0) {
cand = arr[i];
hp = 1;
} else if (arr[i] == cand) {
hp++;
} else {
hp--;
}
}
if (hp == 0) {
return -1;
}
hp = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == cand) {
hp++;
}
}
return hp > arr.length / 2 ? cand : -1;
}
}