[英]all number have been rebeated less than N times
i'm tring to return an array that have all number have been rebeated less than N times.我试图返回一个所有数字都被重复少于 N 次的数组。
expected output : 1,4预期输出:1,4
this is my cod :这是我的鳕鱼:
-- Main -- - 主要的 -
int[] data = {1, 2, 2, 3, 3, 3, 4, 5, 5};
int n = 1;
Solution.solution(data, n);
-- class Solution -- -- 类解决方案 --
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;
}
I would break this down to multiple steps.我会将其分解为多个步骤。
First lets create a countMap
that holds track of all the occurrences:首先让我们创建一个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}
Now all we need to do is to check for the condition count <= n
:现在我们需要做的就是检查条件count <= n
:
List<Integer> resultList = new ArrayList<>();
countMap.forEach((integer, count) -> {
if (count <= n) resultList.add(integer);
});
System.out.println(resultList); // [1, 4]
And last but not least converting the list
back to array
:最后但并非最不重要的是将list
转换回array
:
// {1, 4}
int[] resultArray = resultList.stream()
.mapToInt(Integer::intValue)
.toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.