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 ArrayLis
时间: 2023-07-02 08:12:58 浏览: 126
table_quality.zip_The Program
t containing the integers. The function should return an ArrayList<Integer> containing all the duplicated integers in a, sorted in a descendent order.
实现代码如下:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class DuplicatedPicker {
public static ArrayList<Integer> pick(ArrayList<Integer> a) {
HashSet<Integer> set = new HashSet<>();
ArrayList<Integer> duplicates = new ArrayList<>();
for (int num : a) {
if (!set.add(num)) {
duplicates.add(num);
}
}
Collections.sort(duplicates, Collections.reverseOrder());
return duplicates;
}
}
```
该程序首先使用HashSet来存储所有的整数,并查找重复的数字。如果数字已经存在于集合中,则将其添加到重复列表中。最后,使用Collections.sort方法对重复列表进行逆序排序,然后返回该列表。
阅读全文