Duplicated Numbers 分数 10 作者 翁恺 单位 浙江大学 This program reads a lot of integers, in which may be duplicated numbers. The program picks out all the duplicated ones and sorts the remainders in a descendent order. 函数接口定义: public static ArrayList<Integer> pick(ArrayList<Integer> a); a is the ArrayList to be parsed and returns the result as an ArrayList. Hint: These classes and functions may be used.
时间: 2023-07-02 11:19:18 浏览: 317
Optical bistability and multistability via amplitude and phase control in a Duplicated two-level system
To solve this problem, you can use a HashMap to store the frequency of each number in the ArrayList. Then, iterate through the HashMap to find the numbers that occur more than once and add them to a new ArrayList. Finally, sort the new ArrayList in descending order using Collections.sort() with a custom comparator.
Here's an implementation:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class DuplicatedNumbers {
public static ArrayList<Integer> pick(ArrayList<Integer> a) {
HashMap<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : a) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
ArrayList<Integer> duplicatedNumbers = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > 1) {
duplicatedNumbers.add(entry.getKey());
}
}
Collections.sort(duplicatedNumbers, (a1, a2) -> a2 - a1);
return duplicatedNumbers;
}
}
```
阅读全文