双指针,滑动窗口
100%代码
//1. #include <iostream> #include <vector> using namespace std; int main() { string s; cin >> s; int ans = 0; if (s.size() < 2) { cout << s.size() << endl; return 0; } vector<int>diss(600, -1); int i = 0; int j = 0; for (; j < s.size(); j++) { if (diss[s[j]] != -1) { ans = max(ans, j - i); i = diss[s[j]] + 1; } diss[s[j]] = j; } ans = max(ans, j - i); cout << ans << endl; }
连续子数组的最大和
100%代码
//2. #include <iostream> #include <vector> using namespace std; int main() { vector<int>s; while (1) { int t; cin >> t; s.emplace_back(t); if (getchar() == '\n') break; } int n = s.size(); int temp = 1; int vis = s[0]; for (int i = 1; i < n; i++) { if (s[i] != vis) { temp--; if (temp == 0) { vis = s[i]; temp++; } } else { temp++; } } cout << vis << endl; }
三数之和为零,二分查找前两个数和的相反数,nnlogn
100%代码
//3. #include <iostream> #include <algorithm> #include <vector> #include <set> using namespace std; int main() { //freopen("in.txt", "r", stdin); vector<int>s; while (1) { int t; cin >> t; s.emplace_back(t); if (getchar() == '\n') break; } sort(s.begin(), s.end()); int n = s.size(); for (int i = 0; i < n; i++) { if (i > 0 && s[i] == s[i - 1]) continue; for (int j = i + 1; j < n; j++) { if (j > i + 1 && s[j] == s[j - 1]) continue; int it = lower_bound(s.begin() + j + 1, s.end(), 0 - s[i] - s[j]) - s.begin(); if (it < n && s[it] == (0 - s[i] - s[j])) { cout << s[i] << ' ' << s[j] << ' ' << s[it] << endl; } } } }
全部评论
(0) 回帖