Share my 4 ms cpp solution


  • 0
    O
    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            if (citations.empty()) {
                return 0;
            }
            int N = citations.size();
            sort(citations.begin(), citations.end());
            int start = 0, end = citations[N - 1];
            while (end - start > 1) {
                int mid = start + (end - start) / 2;
                if (check(citations, mid)) {
                    start = mid;
                } else {
                    end = mid;
                }
            }
            if (check(citations, end)) {
                return end;
            } else {
                return start;
            }
        }
    private:
        bool check(const vector<int>& citations, int val) {
            int N = citations.size();
            if (val > N) {
                return false;
            }
            int tmp = citations[N - val];
            return tmp >= val;
        }
    };

Log in to reply
 

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