백준 9728 : Pair sum (Python)

liliili·2022년 11월 7일

백준

목록 보기
22/214

본문 링크

import sys
input=sys.stdin.readline

T=int(input())
for i in range(T):
    N,M=map(int,input().split())

    L=list(map(int,input().split()))

    start= 0 ; end = N-1 ; count=0

    while start<end:

        if L[start]+L[end]>M:
            end-=1
        elif L[start]+L[end]<M:
            start+=1
        else:
            start+=1
            count+=1

    print("Case #%d: %d"%(i+1,count))

📌 어떻게 풀것인가?

리스트가 주어졌을때 두 수의 합이 MM과 같은 경우의 수를 찾는 문제이다.
아주 전형적인 투 포인터 문제이다.
start=0 , end=N-1 , count=0 으로 잡고 두 수의 합이 M보다 크다면 end 를 감소시키고
작다면 start 를 증가시킨다. 만약 두 수의 합이 MM 과 같다면 startcount 를 증가시킨다.

이 문제는 3273 번이랑 똑같은 문제이다.

✅ 코드에서 주의해야할 점

  • while 문 조건에서 start<end로 잡아준다. 투 포인터이기 때문에 두 수는 같을 수 없다.

0개의 댓글