我怎么知道一个数字出现在数组中的频率

ylamdve6  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(280)

我处理保存一个数组中的随机数列表,现在我有一个7个数字的数组:(3,4,6,6,10,3,5),我想知道这些数字出现的频率。
我试过了,但我真的不知道怎么做

int size = 7
int aux [] = {3,4,6,6,10,3,5};
for(int i = 0 ; i<size; i++) {
            int cont = 0 ;
            for(int j = 0; i<size-1; j++) {
                if(aux[i] == aux[j+1]) {
                     aux[j+1] = -1;
                     cont++;
                } 

            }
            System.out.println("The number "+ aux[i] + " appears "+ cont + "times");
        }
dgiusagp

dgiusagp1#

你可以试试这个:

import java.util.*;

public class ArrayCount {

    public static void main(String[] args) {
        int [] a = {3,4,6,6,10,3,5};
        int n = a.length;
        int [] tmp = new int [n];
        System.arraycopy(a, 0, tmp, 0, n); 
        int Num = 1;
        Arrays.sort(tmp);
        for(int i = 1; i < n; i ++) {
            if (tmp[i] != tmp[i-1]) {
                Num ++;
            }
        }
        int [] b1 = new int [Num];      
        int [] b2 = new int [Num];
        for (int i = 0; i < Num; i ++) {
            b2[i] = 1;
        }
        int j = 0;
        for(int i = 1; i < n; i ++) {
            if (tmp[i] == tmp[i-1]) {
                b1[j] = tmp[i];
                b2[j] ++;
            }
            else {
                j ++;
                b1[j] = tmp[i];
            }
        }
        System.out.println("The number of elements in the array: " + Num);
        System.out.println("List of different elements: " + b1);
        System.out.println("List of times of different elements: " + b2);
    }
}
yebdmbv4

yebdmbv42#

创建一个map struct map<integer,integer>,key是你的元素,value是元素在数组中出现的时间。

Map<Integer, Integer> map = new HashMap<>();
    for (int e : array){
        if (map.containsKey(e)){
            map.put(e, map.get(e) + 1);
        } else {
            map.put(e, 1);
        }
    }
    for (Map.Entry<Integer, Integer> e : map.entrySet()){
        System.out.println( e.getKey() + ": " + e.getValue());
    }
guykilcj

guykilcj3#

您可以使用一个Map并在循环中自己计算发生次数:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private static Map<Integer, Integer> getCounts(int[] arr) {
        Map<Integer, Integer> counts = new HashMap<>();
        for (int x : arr) {
            counts.put(x, counts.getOrDefault(x, 0) + 1);
        }
        return counts;
    }

    public static void main(String[] args) {
        int[] arr = {3, 4, 6, 6, 10, 3, 5};
        System.out.println(Arrays.toString(arr));
        Map<Integer, Integer> counts = getCounts(arr);
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            System.out.printf("%d occurs %d %s\n", entry.getKey(), 
                entry.getValue(), entry.getValue() == 1 ? "time" : "times");
        }
    }
}

输出:

[3, 4, 6, 6, 10, 3, 5]
3 occurs 2 times
4 occurs 1 time
5 occurs 1 time
6 occurs 2 times
10 occurs 1 time

相关问题