i'm tring to return an array that have all number have been rebeated less than N times.
expected output : 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:
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
:
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
:
// {1, 4}
int[] resultArray = resultList.stream()
.mapToInt(Integer::intValue)
.toArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.