簡體   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