Share my C++ solutions,easy to understand


  • 0
    V

    Solution(1):

    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            int n = citations.size(), i = 0;
            
            sort(citations.begin(), citations.begin()+n, myComp);
            
            for (i = 0; i < n; ++i)
            {
                if (citations[i] <= i)
                    break;
            }
            
            return i;
        }
        
        static bool myComp(int x, int y)
        {
            return (x > y);
        }
    };
    

    Solution(2):

    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            int i = 0, n = citations.size(), papers = 0;
            vector<int> cnt(n+1, 0);
            
            for (i = 0; i < n; ++i)
            {
                if (citations[i] > n)
                    cnt[n]++;
                else
                    cnt[citations[i]]++;
            }
            
            for (i = n; i >=0; --i)
            {
                papers += cnt[i];
                if (papers >= i)
                    return i;
            }
            return 0;
        }
    };

Log in to reply
 

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