문제접근
•
정렬
•
좌측부터 시작하는 포인터 i 우측부터 시작하는 포인터 j
•
x보다 크면 j를 감소
•
x와 같다면 j를 감소하고 i는 증가
•
x보다 작다면 i 증가
놓쳤던 부분
•
이중포문으로 하나하나 다 비교하는 식으로 진행을 했더니 시간 초과
코드
2416 KB
12 ms
#include <iostream>
#include <vector>
#include <algorithm>
int n, x;
std::vector<int> arr;
int answer = 0;
void input_setting()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
}
void input()
{
std::cin >> n;
arr.resize(n);
for (int i = 0; i < n; i++)
std::cin >> arr[i];
std::cin >> x;
}
void solution()
{
int i = 0;
int j = n - 1;
std::sort(arr.begin(), arr.end());
while (i < j)
{
if (arr[i] + arr[j] > x)
--j;
else if (arr[i] + arr[j] == x)
{
--j;
++i;
++answer;
}
else
++i;
}
}
void print()
{
std::cout << answer;
}
int main(void)
{
input_setting();
input();
solution();
print();
return (0);
}
C++
복사