【演算法】【雙指標】雙指標
阿新 • • 發佈:2020-08-23
雙指標
- 對於一個序列,用兩個指標維護一段區間;
- 對於兩個序列,維護某種次序,比如歸併排序中合併兩個有序序列的操作;
for(int i = 0, j = 0; j < n; j++)
{
//當前維護的區間不滿足條件,i向前移動到滿足條件
while(i < j && check(i, j)) i++;
//具體邏輯
}
最長連續不重複子序列
題目連結:https://www.acwing.com/problem/content/801/
//維護一個區間 #include<iostream> #include<unordered_map> const int N = 100100; int arr[N]; using namespace std; int main() { int n; cin >> n; for(int i = 0; i < n; i++) cin >> arr[i]; unordered_map<int, int> hashmap; int cnt = 0; for(int i = 0, j = 0; j < n; j++) { hashmap[arr[j]]++; while(i < j && hashmap[arr[j]] > 1) { hashmap[arr[i]]--; i++; } cnt = max(cnt, j - i + 1); } cout << cnt << endl; return 0; }
陣列元素的目標和
題目連結:https://www.acwing.com/problem/content/802/
#include <iostream> using namespace std; const int N = 100010; int a[N], b[N]; int main() { int n, m, x; cin >> n >> m >> x; for(int i = 0; i < n; ++i) cin >> a[i]; for(int i = 0; i < m; ++i) cin >> b[i]; for(int i = 0, j = m - 1; i < n; i++) { while(j >= 0 && a[i] + b[j] > x) j--; if(j >= 0 && a[i] + b[j] == x) cout << i << " " << j << endl; } return 0; }