我希望打印出单个数字的出现次数。但问题是,只有计数定义的数字才会打印出来。那么有人可以帮我解决这个问题吗?
public static void main(String[] args) {
int[] numbers = {10,11,9,5,5,3,2,2,1};
int nt = countSingles(numbers);
System.out.println(nt);
}
public static int countSingles(int[]numbers) {
if(numbers == null)return -1;
if(numbers.length<=0)return -1;
int count =1;
for(int i=0; i<numbers.length-1;i++) {
if(numbers[i]<numbers[i++])return -1;
if(numbers[i]>numbers[i++]&&numbers[i++]>numbers[i+2]) {
count++;
}
}
return count;
}
答案 0 :(得分:1)
您可以使用java 8和stream以及 FILTER :
public static void main(String[] args) {
Integer[] numbers = {10,11,9,5,5,3,2,2,1};
Long nt = countSingles(numbers);
System.out.println(nt);
}
public static Long countSingles(Integer[]numbers) {
List<Integer> list = Arrays.asList(numbers);
return list.stream().filter(i->isSingle(i,list)).count();
}
static boolean isSingle(int i, List<Integer> list ){
int occurence=0;
for (Integer aInteger:list) {
if(aInteger==i){
occurence++;
if(occurence>1){
return false;
}
}
}
return true;
}
答案 1 :(得分:0)
你可以试试下面的代码:它也有效,我觉得非常有效,因为我们将使用HashMap
{{1}}
答案 2 :(得分:0)
应计算并存储每个号码的外观。即在地图
int[] numbers = {10, 11, 9, 5, 5, 3, 2, 2, 1};
Map<Integer, List<Integer>> map = Arrays.stream(numbers)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), mapping(identity(), toList())));
然后就可以找到单个数字。
long nt = map.entrySet().stream()
.filter(e -> e.getValue().size() == 1).count();