繁体   English   中英

查找java数组中元素的频率

[英]find the frequency of elements in a java array

我有一个 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..} (对于上面的示例数组);

class MapTest
{
    public static void main(String args[]){
        HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
        int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0};
        for(int i=0; i<arr.length; i++){
            if(h.containsKey(arr[i])){
                h.put(arr[i], h.get(arr[i]) + 1);
            } else {
                h.put(arr[i], 1);
            }
        }
        System.out.println(h);
    }
}

在 Java 8 中你可以这样做

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

你必须做几件事:

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

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

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

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 包可能已经存在,可以检查数组中的频率元素,但这正是您最有可能寻找的。 祝你好运。

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

public static void findCount3(int[] a){
    Map<Integer, Integer> hm = new HashMap<Integer, Integer>();     
    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<len;i++)
        {
            t = in.nextInt();
            arr[i] = t;
        }
        System.out.println("\n");
        for(i=0;i<len;i++)
        {
            count=1;
            for(j=i+1;j<=len-1;j++)
            {
                if(arr[i]==arr[j] && arr[i]!='\0')
                {
                    count++;
                    arr[j] = '\0';
                }
            }
            if(arr[i]!='\0')
            {
                System.out.println(arr[i] + " is " + count + " times.\n");
            }
        }        
    }
}

使用 Java-8,我们可以在一行中找到数组的频率。

Map<Integer, Long> freq = Arrays.stream(a).boxed().
                          collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

此外,由于问题要求我们需要返回一个数组

public Object[] getFrequencies(int[] a) {
    Map<Integer, Long> freq = Arrays.stream(a).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    return freq.entrySet().toArray();
}

我有一个计算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<arr.length;i++)
            {
                System.out.print("arr["+i+"] :  ");
                arr[i]=Integer.parseInt(br.readLine());
            }
            System.out.print("Sorted Array is :");
            SortingArray.sortDescendind(arr);

            for(int i=0;i<arr.length;i++)
            {
                System.out.println("arr["+i+"] :  "+arr[i]);

            }

            for(int i=0;i<arr.length;)
            {
                count=1;
                for(index=i+1;index<arr.length;index++)
                {
                    if(arr[i]==arr[index])
                    {
                        count++;
                    }
                    else{

                        break;
                    }


                }
                System.out.println(""+arr[i] +"----> "+count);
                i+=count;

            }

    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

}

/// 可以为数组选择任意排序方式---->SortingArray.sortDescendind(arr)

您可以计算 HashMap<Element,Frequency> 中每个元素的频率。

Map<Integer,Integer> h = new HashMap<>();
int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0};

for(int elem:arr) {
  h.merge(elem, 1, Integer::sum);
}

Hashmap.merge() 允许您指定如何更新哈希图中的值。 如果 elem 没有现有值,它将类似于 h.put(elem, 1)。 如果存在一个名为 oldFreq 的现有值,它将用 Integer.sum(oldFreq, 1) 替换它

Map<Integer, Integer> map = new HashMap<>();
int arr[] = new int[]{2, 2, 3, 3, 4, 5, 6, 7, 9, 9, 0, 4, 2};

for (int i = 0; i < arr.length; i++) {
    Integer count = map.getOrDefault(arr[i], 0);
    map.put(arr[i], count + 1);
}

//Print the map to see the occurrence
map.forEach((key, value) -> {
    System.out.println(key + " -> " + value);
});
package practice.learning;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM