一问题描述
-
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
-
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
-
示例 1:
-
输入:[3,2,3]
-
输出:3
-
示例 2:
-
输入:[2,2,1,1,1,2,2]
-
输出:2
二示例代码
public static void main(String[] args) {
int[] nums = new int[]{2, 2, 1, 1, 1, 2, 2};
int result = multiElement2(nums);
System.out.println(result);
}
private static int multiElement(int[] nums) {
int mid = nums.length / 2;
for (int i = 0; i < nums.length - 1; i++) {
int count = 1;
int result = -1;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
result = nums[j];
}
}
if (count > mid) {
return result;
}
}
return -1;
}
public static int multiElement2(int[] nums) {
Map<Integer, Integer> counts = countNums(nums);
Map.Entry<Integer, Integer> majorityEntry = null;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
majorityEntry = entry;
}
}
return majorityEntry.getKey();
}
private static Map<Integer, Integer> countNums(int[] nums) {
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
if (!counts.containsKey(num)) {
counts.put(num, 1);
} else {
counts.put(num, counts.get(num) + 1);
}
}
return counts;
}