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 07:12:58 浏览: 65
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方法对重复列表进行逆序排序,然后返回该列表。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)