GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/cpp/1248_count_number_of_nice_sub_arrays.cpp at master · dungquoctrinh/leetcode

Expand file tree

/

1248_count_number_of_nice_sub_arrays.cpp

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
42 lines (40 loc) · 1.02 KB
/

1248_count_number_of_nice_sub_arrays.cpp

Copy path

File metadata and controls

42 lines (40 loc) · 1.02 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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.