Java求解众数问题和重数问题的具体代码
时间: 2024-05-02 22:17:47 浏览: 84
众数问题(求一个数组中出现次数最多的数):
```java
public static int findMode(int[] nums) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("Input array is empty");
}
Map<Integer, Integer> map = new HashMap<>();
int maxCount = 0;
int mode = 0;
for (int num : nums) {
int count = map.getOrDefault(num, 0) + 1;
map.put(num, count);
if (count > maxCount || (count == maxCount && num < mode)) {
maxCount = count;
mode = num;
}
}
return mode;
}
```
重数问题(求一个数组中所有出现次数等于给定值的数):
```java
public static List<Integer> findElementsWithGivenCount(int[] nums, int count) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("Input array is empty");
}
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int c = map.getOrDefault(num, 0) + 1;
map.put(num, c);
}
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == count) {
result.add(entry.getKey());
}
}
return result;
}
```
阅读全文