JAVA中查找一个数组里数字的出现次数
时间: 2024-02-13 21:05:19 浏览: 86
你可以使用一个 HashMap 来记录每个数字出现的次数。具体地,遍历数组,对于数组中的每个数字,检查它是否已经在 HashMap 中。如果在,将该数字的计数器加 1;否则,在 HashMap 中添加该数字并将计数器初始化为 1。遍历结束后,你可以通过遍历 HashMap 来输出每个数字及其出现的次数。
以下是一个示例代码:
```java
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 3, 2, 1, 2, 3, 4, 5};
HashMap<Integer, Integer> count = new HashMap<>();
for (int num : nums) {
if (count.containsKey(num)) {
count.put(num, count.get(num) + 1);
} else {
count.put(num, 1);
}
}
for (HashMap.Entry<Integer, Integer> entry : count.entrySet()) {
System.out.println("Number " + entry.getKey() + " appears " + entry.getValue() + " times.");
}
}
}
```
输出结果为:
```
Number 1 appears 2 times.
Number 2 appears 3 times.
Number 3 appears 3 times.
Number 4 appears 2 times.
Number 5 appears 1 times.
```
阅读全文