在C++中查詢需要翻轉的零,以最大化連續1的個數
在本教程中,我們將找到需要翻轉的零的個數,以在陣列中獲得最大數量的連續1。
我們將使用滑動視窗方法來解決這個問題。讓我們看看解決問題的步驟。
初始化陣列和要翻轉的最大零的個數。
初始化視窗的起始索引、結束索引以及長度。
儲存最大連續1子陣列的長度和起始索引。
迭代陣列,直到結束索引超過陣列長度。
如果零的個數小於最大零的個數,則如果當前值為零,則遞增結束索引和零的個數。
如果零的個數大於最大零的個數,則如果當前值為零,則遞增起始索引並減少零的個數。
如果當前視窗長度大於之前的視窗長度,則更新最大視窗。
迭代陣列並使用視窗起始索引列印零的索引。
示例
讓我們看看程式碼。
#include <bits/stdc++.h>
using namespace std;
void zeroesIndexes(int arr[], int maxZeroes, int n) {
int start = 0, end = 0;
int zeroesCount = 0;
int bestWindowCount = 0, bestWindowStartIndex = 0;
while (end < n) {
if (zeroesCount <= maxZeroes) {
if (arr[end] == 0) {
zeroesCount++;
}
end++;
}
if (zeroesCount > maxZeroes) {
if (arr[start] == 0) {
zeroesCount--;
}
start++;
}
if ((end - start > bestWindowCount) && (zeroesCount <= maxZeroes)) {
bestWindowCount = end - start;
bestWindowStartIndex = start;
}
}
cout << "The indexes are ";
for (int i = 0; i < bestWindowCount; ++i) {
if(arr[bestWindowStartIndex + i] == 0)
cout << bestWindowStartIndex + i << " ";
}
}
int main() {
int arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1};
int maxZeroes= 2;
zeroesIndexes(arr, maxZeroes, 10);
return 0;
}輸出
如果執行上面的程式碼,則會得到以下結果。
The indexes are 5 7
結論
如果您在本教程中遇到任何問題,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP