My 4ms solution is accepted, but I am puzzled now.

  • 0

    Here is my solution:

    class Solution {
        int hIndex(vector<int>& citations) {
            int N = citations.size();
            sort(citations.begin(), citations.end(), greater<int>());
            for (int i=0; i<N; ++i ) { 
                if (citations[i] < i+1) return i;
            return N; //function works fine without this line.  

    I forgot to write return N ( the line with comment ) at first, which should cause the case citations = [1] fail because no value is returned. However, this function still returns 1, which seems correct.

    Moreover, if I wrote

     for (int i=0; i<citations.size(); ++i ) { // instead of i<N

    then for the case citations = [1], this function returns 0.

    I know non-void function without returning value is an undefined behavior in C++. But why the return value is different between using N and using citations.size() ?

Log in to reply

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