【算法】【雙指針】雙指針

雙指針

  1. 對於一個序列,用兩個指針維護一段區間;
  2. 對於兩個序列,維護某種次序,比如歸併排序中合併兩個有序序列的操作;
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;
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章