Java 程序:计算元素出现次数
在本教程中,我们将学习如何在数组中查找元素的出现。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组。
输入: 3 2 1 4 5 6 3 7
输出:
要搜索的元素:3
元素的出现:2
程序 1:查找数组中元素的出现
在这个方法中,我们将看到如何使用循环来查找数组中每个元素的出现。
算法
- 开始
- 声明数组大小。
- 要求用户初始化数组大小。
- 声明数组。
- 要求用户初始化数组元素。
- 输入您想知道其频率的元素。
- 声明一个出现变量并将其初始化为 0。
- 使用 for 循环遍历数组的所有元素。
- 如果元素与数组元素匹配,则增加出现次数。
- 打印每个元素的出现。
- 停止
下面的程序演示了如何使用循环来查找数组中每个元素的出现。
/*Java Program to find the occurence of each element in an array*/
import java.util.*;
import java.util.Arrays;
//Driver Code
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n; //Declare array size
System.out.println("Enter the total number of elements ");
n=sc.nextInt(); //Initialize array size
int arr[]=new int[n]; //Declare array
System.out.println("Enter the elements of the array ");
for(int i=0; i<n ;i++) //Initialize array
{
arr[i]=sc.nextInt();
}
//Enter the element whose frequency you want to know
System.out.println("Enter the element whose frequency you want to know");
int ele=sc.nextInt();
int occ=0;
// Traverse through map and check frequencies
for(int i=0;i<n;i++)
{
if(ele==arr[i])
{
occ++; //Increment the occurrence once the element is found
}
}
//Print the element and its frequency
System.out.println(ele+" occurred "+occ+" times ");
}
}
输入元素总数 10 输入数组的元素 2 7 6 7 8 9 5 7 9 输入你想知道其频率的元素 7 7 出现 4 次
程序 2:查找数组中元素的出现
在这个方法中,我们将看到如何使用 hashmap 来查找数组中每个元素的出现。
算法
- 开始
- 声明数组大小。
- 要求用户初始化数组大小。
- 声明数组。
- 要求用户初始化数组元素。
- 在 hashmap 中插入所有数组元素。
- 遍历数组元素,并使用 for 循环计算频率。
- 输入您想知道其频率的元素。
- 再次遍历映射并检查频率。
- 打印元素的频率。
- 停止
下面的程序演示了如何使用HashMap
来查找数组中每个元素的出现。
/*Java Program to find the occurence of each element in an array*/
import java.util.*;
import java.util.Arrays;
//Driver Code
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n; //Declare array size
System.out.println("Enter the total number of elements ");
n=sc.nextInt(); //Initialize array size
int arr[]=new int[n]; //Declare array
System.out.println("Enter the elements of the array ");
for(int i=0; i<n ;i++) //Initialize array
{
arr[i]=sc.nextInt();
}
Map<Integer, Integer> mp = new HashMap<>();
// Traverse through array elements and count frequencies
for (int i = 0; i < n; i++)
{
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
}
//Enter the element whose frequency you want to know
System.out.println(“Enter the element whose frequency you want to know”);
int ele=sc.nextInt();
int occ=0;
// Traverse through map and check frequencies
for (Map.Entry<Integer, Integer> entry : mp.entrySet())
{
if(ele==entry.getKey())
{
occ=entry.getValue();
}
}
//Print the element and its frequency
System.out.println(ele+" occurred "+occ+" times ");
}
}
输入元素总数 10 输入数组的元素 8 7 6 59 7 9 5 7 9 输入你想知道其频率的元素 9 9 出现 3 次