簡體   English   中英

所有號碼都被重復少於 N 次

[英]all number have been rebeated less than N times

我試圖返回一個所有數字都被重復少於 N 次的數組。

預期輸出:1,4

這是我的鱈魚:

- 主要的 -

 int[] data = {1, 2, 2, 3, 3, 3, 4, 5, 5};
    int n = 1;
        Solution.solution(data, n);

-- 類解決方案 --

public static int[] solution(int[] data, int n) {
        
        int l =  data.length, count = 0;
        int[] Narr = new int[l];
        
        for(int i =0 ; i < l; i++){
            count = 0;
            
            for(int j=1 ; j < l ; j++){
                if(data[i] == data[j]){
                    count++;
                }
                
                if(j == l-1){
                    
                    if(count < n){
                         Narr[i] = data[i];
                         System.out.println(Narr[i]);
                     } 
                }
            }
            
        }
        
        return Narr;
    }

我會將其分解為多個步驟。

首先讓我們創建一個countMap來跟蹤所有事件:

int[] data = {1, 2, 2, 3, 3, 3, 4, 5, 5};
int n = 1;

Map<Integer, Long> countMap = Arrays.stream(data).boxed()
        .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

System.out.println(countMap); // {1=1, 2=2, 3=3, 4=1, 5=2}

現在我們需要做的就是檢查條件count <= n

List<Integer> resultList = new ArrayList<>();
countMap.forEach((integer, count) -> {
    if (count <= n) resultList.add(integer);
});

System.out.println(resultList); // [1, 4]

最后但並非最不重要的是將list轉換回array

// {1, 4}
int[] resultArray = resultList.stream()
        .mapToInt(Integer::intValue)
        .toArray();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM