GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/cpp/1248_count_number_of_nice_sub_arrays.cpp at master · Shaunlipy/leetcode Expand file tree/ Copy path1248_count_number_of_nice_sub_arrays.cppMore file actions 42 lines (40 loc) · 1.02 KB / Copy path1248_count_number_of_nice_sub_arrays.cppFile metadata and controls42 lines (40 loc) · 1.02 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 class Solution { public: int numberOfSubarrays(vector<int>& nums, int k) { return atMostK(nums, k) - atMostK(nums, k - 1); } private: int atMostK(const vector<int>& nums, int k) { int result = 0, left = 0, count = 0; for (int right = 0; right < nums.size(); ++right) { count += nums[right] % 2; while (count > k) { count -= nums[left] % 2; ++left; } result += right - left + 1; } return result; } }; // Time: O(n) // Space: O(k) class Solution2 { public: int numberOfSubarrays(vector<int>& nums, int k) { int result = 0; deque<int> dq = {-1}; for (int i = 0; i < nums.size(); ++i) { if (nums[i] % 2) { dq.emplace_back(i); } if (dq.size() > k + 1) { dq.pop_front(); } if (dq.size() == k + 1) { result += dq[1] - dq[0]; } } return result; } }; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |