找到Noble Integer我在哪里错了? [英] Where am I being wrong in finding Noble Integer?
问题描述
问题陈述:给定一个整数数组,找出数组中是否存在整数p,使得数组中大于的整数数等于p
如果找到这样的整数,则返回1,否则返回-1。
Problem Statement: Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p If such an integer is found return 1 else return -1.
我的代码:
public int solve(ArrayList<Integer> A) {
Collections.sort(A);
for(int i=A.size()-1;i>=0; i--){
if(A.get(i) == (A.size()-i-1))
return 1;
}
return -1;
}
但它为某些输入提供了错误的输出,我无法理解直觉地,当它应该返回-1时返回1。任何人都可以指出我的错误吗?
But it is giving wrong output for the some input which I am unable to understand intuitively.i.e, returning 1 when it should return -1. Can anyone point out my mistake(s)?
推荐答案
感谢所有评论员。我没有仔细观察当某些值相同时会发生什么。我发现的正确解决方案如下。
Thanks to all commentators. I didn't observe carefully what could happen when some values are same. The correct solution I have found is as follows.
public int solve(ArrayList<Integer> A) {
Collections.sort(A);
for(int i=A.size()-1;i>=0; i--){
if(i<A.size()-1 && A.get(i) == A.get(i+1))continue;
if(A.get(i) == (A.size()-i-1))
return 1;
}
return -1;
}
这篇关于找到Noble Integer我在哪里错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!