问题陈述:给定一个整数数组,找出数组中是否存在整数p,使得数组中大于的整数数等于p 如果找到这样的整数,则返回1,否则返回-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。谁能指出我的错误?
答案 0 :(得分:2)
感谢所有评论员。我没有仔细观察当某些值相同时会发生什么。我发现的正确解决方案如下。
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;
}
答案 1 :(得分:2)
请注意在Raku中使用的解决方案,这是您永远不想要的语言。
sub noble( @n )
{
# By @HrBollermann (me)
@n.sort.pairs.grep({ .value + .key == @n.end }).first.value // -1;
}
# Or even shorter,
sub noble( @n )
{
# By @smokemachine
@n.sort(-*).pairs.grep({ .value == .key }).first.value // -1;
}