Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. // Time:  O(n)
  2. // Space: O(n)
  3.  
  4. // Counting sort.
  5. class Solution
  6. {
  7. public:
  8.     int hIndex(vector<int>& citations)
  9.     {
  10.         const auto n = citations.size();
  11.         vector<int> count(n + 1, 0);
  12.         for (const auto& x : citations)
  13.         {
  14.             // Put all x >= n in the same bucket.
  15.             if (x >= n)
  16.             {
  17.                 ++count[n];
  18.             }
  19.             else
  20.             {
  21.                 ++count[x];
  22.             }
  23.         }
  24.  
  25.         int h = 0;
  26.         for (int i = n; i >= 0; --i)
  27.         {
  28.             h += count[i];
  29.             if (h >= i)
  30.             {
  31.                 return i;
  32.             }
  33.         }
  34.         return h;
  35.     }
  36. };
  37.  
  38. // Time:  O(nlogn)
  39. // Space: O(1)
  40. class Solution2
  41. {
  42. public:
  43.     int hIndex(vector<int>& citations)
  44.     {
  45.         sort(citations.begin(), citations.end(), greater<int>());
  46.         int h = 0;
  47.         for (const auto& x : citations)
  48.         {
  49.             if (x >= h + 1)
  50.             {
  51.                 ++h;
  52.             }
  53.             else
  54.             {
  55.                 break;
  56.             }
  57.         }
  58.         return h;
  59.     }
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement