Two Pointers

# 2 つのポインタを使う

ソート済み の整数配列から,和が $X$ となるような 2 要素を選ぶ問題を解く.

ナイーブなやり方は全探索で $O(n^2)$ かかる.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;

int main() {
  int n; cin >> n;
  int x; cin >> x;
  vector<int> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  sort(a.begin(), a.end());

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (a[i] + a[j] == x) {
        cout << a[i] << " + " << a[j] << endl;
      }
      if (x < a[i] + a[j]) break;
    }
  }
  cout << "non" << endl;
  return 0;
}

2 つのポインタで左右から探しに行くと $O(n)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <bits/stdc++.h>
using namespace std;

int main() {
  int n; cin >> n;
  int x; cin >> x;
  vector<int> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  sort(a.begin(), a.end());

  int i = 0, j = n-1;
  while (i < j) {
    if (a[i] + a[j] == x) {
      cout << a[i] << " + " << a[j] << endl;
    } else if (a[i] + a[j] < x) i++;
    else j--s;
  }
  return 0;
}
Hugo で構築されています。
テーマ StackJimmy によって設計されています。