배열을 입력받고 오름차순으로 정렬 후 투포인터 알고리즘을 이용해서 두 원소의 합이 0에 가장 가까운 두 원소를 찾는 알고리즘
두 원소의 합이 0보다 크면 결과값이 현재보다 작아야 하니 작은 원소가 필요할 것이고 그에따라 right--를 해준다.
left도 마찬가지로 left++ 연산
6
-99 -2 -1 2 98 100
-99+100 = 1
-99 + 98 = -1
-2 + 98 = 96
-2 + 2 = 0 (끝)
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int num;
int arr[100000];
void Func()
{
sort(arr, arr+num);
int left = 0;
int right = num-1;
int temp;
int result = 2000000000;
int tempLeft, tempRight;
while(left < right)
{
temp = arr[left] + arr[right];
if(abs(temp) < result)
{
tempLeft = arr[left];
tempRight = arr[right];
result = abs(temp);
if(result == 0)
break;
}
if(temp > 0)
right--;
else if(temp < 0)
left++;
}
printf("%d %d", tempLeft, tempRight);
}
int main(int argc, char* argv[]) {
scanf("%d", &num);
for(int i=0; i<num; i++)
scanf("%d", &arr[i]);
Func();
return 0;
}