Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 22a093e

Browse files
committed
Add C++ solutions for leetcode 1004.
1 parent 9bf757e commit 22a093e

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int longestOnes(vector<int>& nums, int k) {
9+
const int N = nums.size();
10+
int i = 0; // i: 滑动窗口左边界, 固定右边界, 移动左边界
11+
int count = 0; // 已经使用了多少次反转次数
12+
int res = 0; // res: max len
13+
for (int j = 0; j < N; j++)
14+
{
15+
if (nums[j] == 1) // 新加入窗口右侧的数是1, 不需要使用反转次数
16+
res = max(res, j - i + 1);
17+
else {
18+
count++;
19+
while (count > k) // 此时使用的反转次数超了, 需要移动左边界, 直到窗口使用的反转次数减小回到k为止
20+
{
21+
if (nums[i] == 0)
22+
count--;
23+
i++;
24+
}
25+
res = max(res, j - i + 1);
26+
}
27+
}
28+
return res;
29+
}
30+
};
31+
32+
// Test
33+
int main()
34+
{
35+
Solution sol;
36+
vector<int> nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0};
37+
int k = 2;
38+
auto res = sol.longestOnes(nums, k);
39+
cout << res << endl;
40+
41+
return 0;
42+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int longestOnes(vector<int>& nums, int k) {
9+
const int N = nums.size();
10+
int left = 0; // left: 滑动窗口左边界, 固定右边界, 移动左边界
11+
int j = 0; // j: 滑动窗口右边界right
12+
int preSum = 0; // 使用的反转次数 0 -> 1
13+
int res = 0;
14+
for (int j = 0; j < N; j++)
15+
{
16+
preSum += (nums[j] == 0 ? 1 : 0);
17+
if (preSum > k) // 一开始, 让反转次数达到k+1, 然后开始根据情况收缩左边界
18+
{
19+
while (left < j && nums[left] == 1) /* 在左边界每遇到一个1, 就直接移动左边界, 如果遇到1个0, 翻转次数又新腾出了1, 需要先更新preSum的值 */
20+
left++;
21+
22+
preSum -= 1;
23+
left++;
24+
}
25+
res = max(res, j - left + 1); // 此时, 反转次数恰好恢复到k, 可以更新结果了
26+
}
27+
return res;
28+
}
29+
};
30+
31+
// Test
32+
int main()
33+
{
34+
Solution sol;
35+
vector<int> nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0};
36+
int k = 2;
37+
auto res = sol.longestOnes(nums, k);
38+
cout << res << endl;
39+
40+
return 0;
41+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /