C++ Solution


  • 0
    Y

    Sort the vector first. Now 'citations.size()-i' is the number of papers with at least citations[i] citations. For the given example [3,0,6,1,5], the sorted vector is [0,1,3,5,6]. When i=1, there are num=citations.size()-i=5-1=4 papers with at least 1 citations. So h-index is 1. When i=2, there are num=5-2=3 papers with at least 3 citations. So h-index is 3.

    If citations[i] are very big, for instance [11,13,15], when i=0, num=3-0=3. We use num as h-index instead.

    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            
            int h=0;
            sort(citations.begin(), citations.end());
            for (int i=0; i<citations.size(); i++) {
                if (citations[i] > 0) {
                    int num = citations.size()-i;
                    if (num >= citations[i]) {
                        h = max(h, citations[i]);
                    }
                    else {
                        h = max(h, num);
                        break;
                    }
                }
            }
            return h;
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.