力扣169-多数元素

题目描述

169. 多数元素

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

1
2
输入:nums = [3,2,3]
输出:3

示例 2:

1
2
输入:nums = [2,2,1,1,1,2,2]
输出:2

提示:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

解题思路

哈希表

我们使用哈希映射(HashMap)来存储每个元素以及出现的次数。对于哈希映射中的每个键值对,键表示一个元素,值表示该元素出现的次数。

我们用一个循环遍历数组 nums 并将数组中的每个元素加入哈希映射中。在这之后,我们遍历哈希映射中的所有键值对,返回值最大的键。我们同样也可以在遍历数组 nums 时候使用打擂台的方法,维护最大的值,这样省去了最后对哈希映射的遍历。

排序

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution169Case1 {
private static final Map<Integer, Integer> map = new HashMap<>();

public static int majorityElement(int[] nums) {
for (int num : nums) {
map.merge(num, 1, Integer::sum);
}
int max = nums.length / 2 + 1;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() >= max) {
return entry.getKey();
}
}
return -1;
}

public static void main(String[] args) {
int[] nums = {2, 2};
System.err.println(majorityElement(nums));
}
}
1
2
3
4
5
6
7
8
9
10
11
public class Solution169Case2 {
public static int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}

public static void main(String[] args) {
int[] nums = {2, 2};
System.err.println(majorityElement(nums));
}
}