找到java数组中元素的频率

我有一个int数组:

{1,2,4,2,3,5,6,4,3} 

如何找到数组元素的频率,如1=1,2=2,3=2,4=4.. 我需要一个类,我可以传递我的数组并返回一个数组,它给出了数组元素的数量。 例如: – array{[0]=1,[1]=2,[2]=3,[3]=4..} (对于上面的例子数组);

你必须做一些事情:

  1. 定义数字范围的上限和下限。
  2. 建立一个方便的对象/数据结构来存储这些数字的出现次数。
  3. 迭代传入的数组并计算每个数字的所有出现次数,将结果存储在方便的对象/数据结构中。

如果以简单的方式完成,则只需从传入的数组中读取元素并打印出最终结果即可。

 class MapTest { public static void main(String args[]){ HashMap h = new HashMap(); int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0}; for(int i=0; i 

没有放弃这里是一个很好的起点:

 int[] array = {1,2,4,2,3,5,6,4,3}; public int[] (array){ //need to perform a sort...or a search //after searching check for matches, //sorting could make performing comparisons more efficient //not all searches/sorts are created equal. int[array.length] result += {"["+numberChecked+"]="+freqOccurred}; return result; } 

此代码尚未编译,因此将其视为伪代码。 目的是让您思考如何实现预期目标。 可能已经存在一个可以检查数组中频率元素的java包,但这是您最有可能寻找的。 祝好运。

在Java 8中,您可以执行此操作

 Map freq = Arrays.stream(array).boxed(). collect(Collectors.groupingBy(Integer::intValue, Collectors.counting())); 

如果指定了数组元素的范围并限制为数组大小,则最佳解决方案是使用哈希映射。 T(n)= O(n),辅助空间= O(n)。

 public static void findCount3(int[] a){ Map hm = new HashMap(); for(int i = 0; i < a.length; i++){ if(!hm.containsKey(a[i])){ hm.put(a[i], 1); }else{ hm.put(a[i], hm.get(a[i])+1); } System.out.println(hm); } 
 import java.util.*; class Findfreqarray { public static void main(String args[]) { int t, i, j, len, count=0; Scanner in = new Scanner(System.in); System.out.println("Enter number of elements to insert in an array: "); len = in.nextInt(); int[] arr = new int[len]; System.out.println("Enter elements to insert in an array: "); for(i=0;i 

我有一个解决方案来计算java数组中元素的频率

 import java.io.BufferedReader; import java.io.InputStreamReader; public class ItemCount { public static void main(String[] args) { try{ int count=1,index=1; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the Size of array : "); int size=Integer.parseInt(br.readLine()); System.out.print("Enter the Elements of array : "); int arr[]=new int[size]; for(int i=0;i "+count); i+=count; } }catch(Exception ex) { ex.printStackTrace(); } } } 

///你可以为数组选择任何排序方法—-> SortingArray.sortDescendind(arr)