6-3 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> pi
时间: 2023-07-02 08:09:03 浏览: 732
ecewiseDuplicatedNumbers(int[] nums)
其中,
输入参数:
int[] nums :整型数组,表示输入的一组整数。
输出参数:
ArrayList<Integer> :整型数组列表,表示所有重复出现过的整数,按照降序排列。
示例:
输入:nums = {3, 1, 2, 3, 4, 5, 2, 4}
输出:[4, 3, 2]
解释:其中,4、3、2 都是重复出现过的整数,按照降序排列后,输出为 [4, 3, 2]。
算法思路:
1. 使用HashMap记录每个数字出现的次数;
2. 遍历HashMap,将出现次数大于1的数字加入到ArrayList中;
3. 对ArrayList进行降序排列,返回结果。
Java代码实现:
相关问题
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.
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;
}
}
```
duplicated numbers 分数 10 作者 翁恺 单位 浙江大学 this program reads a lot
of integers and checks whether there are any duplicates. If there are duplicates, it prints "YES", otherwise it prints "NO". Here's the code:
```python
n = int(input())
a = list(map(int, input().split()))
s = set(a)
if len(a) != len(s):
print("YES")
else:
print("NO")
```
The program first reads in the number of integers `n`, and then reads in `n` integers. It then converts the input into a list `a`, and creates a set `s` from `a`. Since sets only contain unique elements, if the length of `a` is not equal to the length of `s`, it means that there are duplicates, and the program prints "YES". Otherwise, the program prints "NO".
阅读全文