在Java中獲取陣列中最頻繁的元素
在Java中,陣列是一種非原始資料型別,它儲存相同資料型別的多個值。
根據題目要求,我們需要找出陣列中出現次數最多的元素及其頻率。
陣列可以包含重複值。元素在陣列中出現的次數稱為該元素的頻率。頻率最高的元素就是陣列中最頻繁的元素。
讓我們看看如何使用Java程式語言來實現。
一些示例
示例1
Suppose the original array is {1, 2, 3, 1, 5, 7, 5, 5, 9}.
執行查詢陣列中出現次數最多的元素的操作後,結果將是:
最頻繁的元素是:5
示例2
Suppose the original array is {7, 2, 3, 2, 5, 7, 3, 5, 9}.
執行查詢陣列中出現次數最多的元素的操作後,結果將是:
最頻繁的元素是:7
示例3
Suppose the original array is {77, 22, 45, 22, 32, 77, 45, 77, 77}
執行查詢陣列中出現次數最多的元素的操作後,結果將是:
最頻繁的元素是:77
演算法
步驟1 - 宣告並初始化一個整型陣列。
步驟2 - 使用一個int變數 `max_count` 並將其初始化為0。再宣告另一個int變數 `count` 來跟蹤元素在陣列中出現的次數。
步驟3 - 檢查條件 `count > max_count`。如果是,則將 `count` 的值賦給 `max_count`。
步驟4 - 最後,列印具有 `max_count` 值的元素。
語法
要獲取陣列的長度(陣列中的元素個數),可以使用陣列的內建屬性 `length`。
以下是其語法:
array.length
其中,'array' 指的是陣列引用。
多種方法
我們提供了不同的方法來解決這個問題。
使用靜態初始化陣列元素
使用使用者自定義方法
讓我們逐一檢視程式及其輸出。
方法1:使用靜態初始化陣列元素
示例
在這種方法中,陣列元素將在程式中初始化。然後,根據演算法獲取陣列中最頻繁的元素。
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the array elements
int[] arr = { 1, 2, 3, 1, 5, 7, 5, 5, 9 };
//get the length of the array
int n = arr.length;
int max_count = 0;
int maxfreq = 0;
//Logic implementation
for (int i = 0; i < n; i++){
int count = 0;
for (int j = 0; j < n; j++){
if (arr[i] == arr[j]){
count++;
}
}
if (count > max_count){
max_count = count;
maxfreq = arr[i];
}
}
//print the result
System.out.print("Most frequent element is: " + maxfreq);
}
}
輸出
Most frequent element is: 5
方法2:使用使用者自定義方法
示例
在這種方法中,陣列元素將在程式中初始化。然後,透過將陣列作為引數傳遞給使用者自定義方法,並在方法內部根據演算法獲取陣列中最頻繁的元素。
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the array elements
int[] arr = { 1, 2, 3, 1, 5, 7, 5, 5, 9 };
//get the length of the array
int n = arr.length;
//call the user defined method and print the result
System.out.print("Most frequent element is: " + freq(arr, n));
}
//user defined method
public static int freq(int[] arr, int n){
int max_count = 0;
int maxfreq = 0;
//Logic implementation
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > max_count) {
max_count = count;
maxfreq = arr[i];
}
}
return maxfreq;
}
}
輸出
Most frequent element is: 5
在本文中,我們探討了如何在Java中查詢陣列中最頻繁的元素。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP