从标题中可以看出,我需要找到最长的二进制子序列的长度,最多为k
个。例如:
k = 3
,binary_seq = 11100001101011010000011
,答案是:10(因为最长的子序列是11100001101 0110100000 11)
k = 1
,binary_seq = 00101001001
,答案是:5(因为最长的子序列是00101 00100 1)
我做了但是在二次时间(我猜)
#include <iostream>
#include <vector>
using namespace std;
template <typename V>
void pop_front(V & v)
{
v.erase(v.begin());
}
int main() {
int k,maxLength=0,lengthOfSequence;
bool one;
string bin_seq;
lengthOfSequence = 1;
vector<unsigned> myList;
cin >> k;
cin >> bin_seq;
for(char num : bin_seq) {
myList.push_back(0);
if (num == '1') {
for(int i = 0; i < lengthOfSequence;++i)
++myList[i];
}
for(int i = 0; i < lengthOfSequence;++i) {
if(myList[i] <= k) {
if (lengthOfSequence-i > maxLength) {
maxLength = lengthOfSequence-i;
}
}
}
lengthOfSequence++;
while(myList[0]>k) {
pop_front(myList);
lengthOfSequence--;
}
}
cout << maxLength << '\n';
return 0;
}
如何以较小的时间复杂度做到这一点?
答案 0 :(得分:4)
您可以使用此算法在O(n)中执行此操作:
end
索引来扩展序列,直至到达k+1
- st 1
k+1
- st 1
之前,将序列缩小为&#34;拉入&#34;开始跳过序列中最早的1
end
扩展序列时,记录序列的最大长度max
将包含最长的子序列,其中包含最多k
个。答案 1 :(得分:1)
让我们说输入是1101011010000011
1101011010000011
fedcba9876543210 << Bit Positions
现在创建一个包含索引的数组。保持i and j
为j = (i + k-1)
,同时将两者推进为1。
For K = 3
Array: 0 1 7 9 a c e f
i,j: ^ ^
max = 9 - (0-1) - 1
-----------------------
0 1 7 9 a c e f
i++,j++: ^ ^
max = (arr[j+1] - arr[i-1]) - 1
= a - 0 - 1 = 9
-----------------------
0 1 7 9 a c e f
^ ^
max = (arr[j+1] - arr[i-1]) - 1
= c - 1 - 1 = 12- 1- 1 = 10 (as 10 > 9)
-----------------------
0 1 7 9 a c e f
^ ^
max = (e - 7) - 1 = 14 - 7 - 1 = 6. So max = 10
-----------------------
0 1 7 9 a c e f
^ ^
max = f-9 - 1 = 15-9-1 = 5 (<10).
-----------------------
0 1 7 9 a c e f
^ ^
max = (f+1) - a - 1 = 16-10-1 = 5 (<10).
So, max = 10;