Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - Where am I being wrong in finding Noble Integer?

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.

My code:

     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;
    }

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...