面试 19：输出数组中出现次数超过一半的数字（剑指 Offer 26 题）

准备测试用例

1. 输入符合条件的数组，查看打印是否满足情况；
2. 输入不符合条件的数组，查看打印；
3. 输入只有一个元素的数组，查看打印；
4. 输入无效数组，查看打印；

思考程序逻辑

``````public class Test19 {
private static int moreThanHalfNums(int[] nums) {
if (nums == null || nums.length == 0)
throw new RuntimeException("the length of array must be large than 0");
int len = nums.length;
Map<Integer, Integer> map = new HashMap<>();

for (int num : nums) {
if (map.containsKey(num))
map.put(num, map.get(num) + 1);
else
map.put(num, 1);
}
int times = len / 2;
// 查找 map 中 value 最大的值
for (Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > times)
return entry.getKey();
}
throw new RuntimeException("invalid input!");
}

public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 2, 2, 4, 2, 2, 5};
System.out.println(moreThanHalfNums(nums1));
int[] nums2 = {1};
System.out.println(moreThanHalfNums(nums2));
int[] nums3 = {2, 1, 2, 1, 2, 2, 3, 2, 1};
System.out.println(moreThanHalfNums(nums3));
int[] nums4 = {1, 2, 3, 4, 5};
System.out.println(moreThanHalfNums(nums4));
}
}
``````

``````public class Test19 {

private static int moreThanHalfNums(int[] nums) {
if (nums == null || nums.length == 0)
throw new RuntimeException("the length of array must be large than 0");
int result = nums[0];
int times = 1;
int len = nums.length;
for (int i = 1; i < len; i++) {
if (times == 0) {
result = nums[i];
times = 1;
} else if (result == nums[i])
times++;
else
times--;
}
times = 0;
for (int num : nums) {
if (num == result)
times++;
}
if (times > len / 2)
return result;
throw new RuntimeException("invalid input!");
}

public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 2, 2, 4, 2, 2, 5};
System.out.println(moreThanHalfNums(nums1));
int[] nums2 = {1};
System.out.println(moreThanHalfNums(nums2));
int[] nums3 = {2, 1, 2, 1, 2, 2, 3, 2, 1};
System.out.println(moreThanHalfNums(nums3));
int[] nums4 = {1, 2, 3, 4, 5};
System.out.println(moreThanHalfNums(nums4));
}
}
``````