Today Sangmin Learned
728x90

1. 링크

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

2. 난이도(solved.ac 참고)

실버3

3. 풀이

# https://www.acmicpc.net/problem/3273
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
x = int(input())
count = 0
first = 0
last = len(a)-1
a.sort()
while first < last:
if a[first] + a[last] > x:
last -= 1
elif a[first] + a[last] < x:
first += 1
else:
count += 1
last -= 1
first += 1
print(count)
view raw 두수의합.py hosted with ❤ by GitHub

처음에 조합을 이용해서, aC2를 한 두 개의 합이 x일 경우 count를 +1 해줬는데, 그렇게 하니까 시간초과가 떴다.

그래서, sort 후에 투 포인터를 사용해서 합보다 작으면 last 값을 -1, 크면 first 값을 +1, 같으면 last값 감소와 first값 증가를 동시에 해줬다.

profile

Today Sangmin Learned

@steadily-worked

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!