| 12 | * |
| 13 | * */ |
| 14 | public class Code01_SuperWaterKing { |
| 15 | |
| 16 | // 用哈希表对出现的数做词频统计 |
| 17 | // 最后遍历哈希表,自然知道有没有水王数,水王数是谁 |
| 18 | // 该方法不符合题目的限制,因为使用了哈希表,所以额外空间复杂度O(N) |
| 19 | // 但是该方法功能正确,仅作为对数器使用,用于验证下面的waterKing方法 |
| 20 | public static int verify(int[] arr) { |
| 21 | if (arr == null || arr.length == 0) { |
| 22 | return -1; |
| 23 | } |
| 24 | HashMap<Integer, Integer> map = new HashMap<>(); |
| 25 | for (int num : arr) { |
| 26 | if (map.containsKey(num)) { |
| 27 | map.put(num, map.get(num) + 1); |
| 28 | } else { |
| 29 | map.put(num, 1); |
| 30 | } |
| 31 | } |
| 32 | int N = arr.length; |
| 33 | for (Entry<Integer, Integer> record : map.entrySet()) { |
| 34 | if (record.getValue() > (N >> 1)) { |
| 35 | return record.getKey(); |
| 36 | } |
| 37 | } |
| 38 | return -1; |
| 39 | } |
| 40 | |
| 41 | // 真正想实现的方法 |
| 42 | public static int waterKing(int[] arr) { |
| 43 | if (arr == null || arr.length == 0) { |
| 44 | return -1; |
| 45 | } |
| 46 | int candidate = 0; |
| 47 | int restHP = 0; |
| 48 | for (int cur : arr) { |
| 49 | if (restHP == 0) { // 如果没有候选 |
| 50 | candidate = cur; |
| 51 | restHP = 1; |
| 52 | } else if (cur != candidate) { // 如果有候选,并且当前的数字和候选不一样 |
| 53 | restHP--; |
| 54 | } else { // 如果有候选,并且当前的数字和候选一样 |
| 55 | restHP++; |
| 56 | } |
| 57 | } |
| 58 | // 如果遍历完成后,没有候选留下来,说明没有水王数 |
| 59 | if (restHP == 0) { |
| 60 | return -1; |
| 61 | } |
| 62 | // 如果有候选留下来,再去遍历一遍,得到候选真正出现的次数 |
| 63 | int count = 0; |
| 64 | for (int num : arr) { |
| 65 | if (num == candidate) { |
| 66 | count++; |
| 67 | } |
| 68 | } |
| 69 | int N = arr.length; |
| 70 | // 如果候选真正出现的次数大于N/2,返回候选 |
| 71 | // 否则返回-1代表没有水王数 |
nothing calls this directly
no outgoing calls
no test coverage detected