求不重复数字中出现最多的数字及出现次数
时间: 2024-06-10 08:03:51 浏览: 60
好的,请稍等,让我思考一下......
经过计算,我得出结论:如果给定一个不重复的数字列表,那么出现最多的数字及出现次数将是1,出现了1次。
如果是给定一个有重复数字的列表,那么需要先去掉重复的数字,然后再计算出现次数。比如,对于列表[3, 2, 1, 2, 4, 1, 5, 6, 2],去掉重复数字后得到[3, 2, 1, 4, 5, 6],其中出现最多的数字是2,出现了3次。
希望我的答复能对您有所帮助。
相关问题
请用java语言写出在1-80的数字中随机选取20个不重复的数,多次重复上述过程,给出出现次数最多的10个数并排序
以下是一个 Java 代码示例,可以实现在 1-80 的数字中随机选取 20 个不重复的数,多次重复上述过程,统计出现次数最多的 10 个数并排序:
```java
import java.util.*;
public class RandomNumber {
public static void main(String[] args) {
// 选取 20 个不重复的随机数
Set<Integer> set = new HashSet<>();
Random rand = new Random();
while (set.size() < 20) {
int num = rand.nextInt(80) + 1;
if (!set.contains(num)) {
set.add(num);
}
}
System.out.println("随机选取的 20 个数为:" + set);
// 进行 m 次重复计算
int m = 100;
Map<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < m; i++) {
List<Integer> list = new ArrayList<>(set);
Collections.shuffle(list);
for (int j = 0; j < 10; j++) {
int num = list.get(j);
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
}
// 统计出现次数最多的 10 个数并排序
List<Map.Entry<Integer, Integer>> countList = new ArrayList<>(countMap.entrySet());
Collections.sort(countList, (a, b) -> b.getValue().compareTo(a.getValue()));
System.out.println("出现次数最多的 10 个数为:");
for (int i = 0; i < 10; i++) {
System.out.println(countList.get(i).getKey() + " 出现次数为 " + countList.get(i).getValue());
}
}
}
```
这段代码的思路与上一个示例类似,不同之处在于进行了 m 次重复计算,并将每次计算的结果累加到 countMap 中,最后统计出现次数最多的 10 个数并排序。
请用java语言写出在1-80的数字中随机选取20个不重复的数,经过n次计算,给出出现次数最多的10个数并排序
以下是一个 Java 代码示例,可以实现在 1-80 的数字中随机选取 20 个不重复的数,经过 n 次计算,统计出现次数最多的 10 个数并排序:
```java
import java.util.*;
public class RandomNumber {
public static void main(String[] args) {
// 选取 20 个不重复的随机数
Set<Integer> set = new HashSet<>();
Random rand = new Random();
while (set.size() < 20) {
int num = rand.nextInt(80) + 1;
if (!set.contains(num)) {
set.add(num);
}
}
System.out.println("随机选取的 20 个数为:" + set);
// 进行 n 次计算
int n = 10000;
Map<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>(set);
Collections.shuffle(list);
for (int j = 0; j < 10; j++) {
int num = list.get(j);
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
}
// 统计出现次数最多的 10 个数并排序
List<Map.Entry<Integer, Integer>> countList = new ArrayList<>(countMap.entrySet());
Collections.sort(countList, (a, b) -> b.getValue().compareTo(a.getValue()));
System.out.println("出现次数最多的 10 个数为:");
for (int i = 0; i < 10; i++) {
System.out.println(countList.get(i).getKey() + " 出现次数为 " + countList.get(i).getValue());
}
}
}
```
这段代码的思路是:首先使用 HashSet 选取 20 个不重复的随机数,然后进行 n 次计算,每次从这些数中随机选择 10 个数,并统计每个数出现的次数,最后使用 ArrayList 和 Collections.sort() 方法对出现次数进行排序,输出出现次数最多的 10 个数。