Java代码演示:一个数组找出出现次数最多的一个数,如果多个数出现的次数相同则输出第一个
时间: 2023-12-06 09:44:47 浏览: 45
以下是Java代码演示:
```java
public class MaxOccurrence {
public static int findMaxOccurrence(int[] arr) {
int n = arr.length;
int maxCount = 0;
int maxElement = arr[0];
int currCount = 1;
for (int i = 0; i < n; i++) {
if (i < n - 1 && arr[i] == arr[i + 1]) {
currCount++;
} else {
if (currCount > maxCount) {
maxCount = currCount;
maxElement = arr[i];
}
currCount = 1;
}
}
return maxElement;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 4, 3, 2, 1, 4, 5, 5};
int maxElement = findMaxOccurrence(arr);
System.out.println("The element with maximum occurrence is: " + maxElement);
}
}
```
这个程序中,我们首先定义了一个 `findMaxOccurrence` 方法,该方法接收一个整型数组作为参数,并返回该数组中出现次数最多的元素。如果有多个元素出现次数相同,则返回第一个元素。
在方法中,我们遍历整个数组并使用一个计数器 `currCount` 记录当前元素出现的次数。如果当前元素与下一个元素相同,则计数器加1。否则,我们将当前计数器的值与当前最大计数器的值进行比较。如果当前计数器的值更大,则更新最大计数器的值和最大元素的值。最后,我们将当前计数器的值重置为1,并继续遍历数组。
在 `main` 方法中,我们创建一个示例数组并调用 `findMaxOccurrence` 方法来查找出现次数最多的元素,并打印结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)