[백준 3273번 C/C++] 두 수의 합

 

https://www.acmicpc.net/problem/3273

 

3273번: 두 수의 합

n개의 서로 다른 양의 정수 a1, a2, ..., an으로 이루어진 수열이 있다. ai의 값은 1보다 크거나 같고, 1000000보다 작거나 같은 자연수이다. 자연수 x가 주어졌을 때, ai + aj = x (1 ≤ i < j ≤ n)을 만족하는

www.acmicpc.net


 

 

해결방안

 

투 포인터 알고리즘 

 


 

코드

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, x;
vector<int> a;
int answer;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> n;
	a.resize(n);
	for(int i = 0; i< n; i++){
		cin >> a[i];
	}
	cin >> x;

	sort(a.begin(), a.end()); // 1 2 3 5 7 9 10 11 12 정렬

	int left = 0, right = n - 1;
	while (left < right)
	{
		if (a[left] + a[right] == x){
			answer++;
			left++;
		}
		else if (a[left] + a[right] < x){
			left++;
		}
		else if (a[left] + a[right] > x){
			right--;
		}
	}

	cout << answer;

	return 0;
}