[Boj]3273번 : 두 수의 합
2024. 8. 4. 13:31ㆍAlgorithm
1. problem :
https://www.acmicpc.net/problem/3273
2. solution 1 :
def count_pairs_with_sum(arr, x):
arr.sort()
left = 0
right = len(arr) - 1
count = 0
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == x:
count += 1
left += 1
right -= 1
elif current_sum < x:
left += 1
else:
right -= 1
return count
# 입력 받기
n = int(input())
arr = list(map(int, input().split()))
x = int(input())
# 쌍의 개수 출력
print(count_pairs_with_sum(arr, x))
two-pointer를 이용한 방법.
3. solution 2 :
n = int(input())
nums = list(map(int,input().split()))
x = int(input())
count = 0
hashMap = {}
for i in range(n):
target = x - nums[i]
if target in hashMap:
if hashMap[target] == 1 :
del hashMap[target]
else:
hashMap[target] -= 1
count += 1
else:
hashMap[nums[i]] = 1
hashMap을 이용한 방법
'Algorithm' 카테고리의 다른 글
[Boj]11326:Strfry (0) | 2024.08.04 |
---|---|
[Boj] 10807번 : 개수 세기 (0) | 2024.08.04 |
[Boj]1475 :방 번호 (0) | 2024.08.04 |
[Leetcode]981. Time Based Key-Value Store (0) | 2024.08.03 |
[Leetcode]1493. Longest Subarray of 1's After Deleting One Element (0) | 2024.08.03 |