leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0922.cpp (538B)


      1 class Solution {
      2     int atMost(const vector<int> &nums, int k) {
      3         static int seen[20001] = {0};
      4         memset(seen, 0x00, sizeof(seen));
      5 
      6         int res = 0, j = 0;
      7         for (int i = 0; i < nums.size(); i++) {
      8             if (!seen[nums[i]]++) k--;
      9             while (k < 0)
     10                 if (!--seen[nums[j++]]) k++;
     11             res += i - j + 1;
     12         }
     13         return res;
     14     }
     15 
     16   public:
     17     int subarraysWithKDistinct(const vector<int> &nums, int k) {
     18         return atMost(nums, k) - atMost(nums, k - 1);
     19     }
     20 };