Given an array with around 10w elements, each element is within [0,10w], how to get max subsequense length with same value if you have a opportunity to swap two elements?
Sampes:
1,1,0,2,3,1,0,1,1,3,4 => output: 4
0,2,3,1,0,1,1,3,4 => output: 3
1,1,0,0,2,3,3,1 => output: 3
这道题目参考Leetcode 1156. 单字符重复子串的最大长度
而这道题的思路是用Leetcode 424. 替换后的最长重复字符 的思路改造过来,不是直接进行交换,而是最后特判一下是否一定能交换。
Leetcode 424
class Solution {
public:
int characterReplacement(string s, int k) {
// 维护一个滑动窗口i,j
// 维护这个滑动窗口中出现次数最多的元素(需要HashMap以及一个变量)
// 这个窗口的大小一定小于maxLen+k
int maxlength = 0;
int Hash[26] = {0};
int maxLen = 0, res = 0;
for(int i=0,j=0;j<s.size();j++){
Hash[s[j]-'A']++;
maxLen = max(maxLen, Hash[s[j]-'A']);
while(i<j && j-i+1-maxLen>k)
Hash[s[i++]-'A']--;
res = max(res,j-i+1);
}
return res;
}
};
Leetcode 1156
class Solution {
public:
int maxRepOpt1(string s) {
int maxlength = 0;
int Hash[26] = {0};
int maxLen = 0, res = 0, k =1;
for(int i=0,j=0;j<s.size();j++){
Hash[s[j]-'a']++;
maxLen = max(maxLen, Hash[s[j]-'a']);
while(i<j && j-i+1-maxLen>k)
Hash[s[i++]-'a']--;
res = max(res,j-i+1);
}
int hashmap[26] = {0};
maxLen = 0;
for(auto c:s) {
hashmap[c-'a']++;
maxLen = max(maxLen,hashmap[c-'a']);
}
return min(maxLen,res);
}
};
来源:oschina
链接:https://my.oschina.net/u/4266314/blog/4540334