Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...