3273: 두 수의 합

알고리즘/백준
2024. 3. 23. 00:50
728x90

1 ≤ n ≤ 100000, 1 ≤ x ≤ 2000000

n은 입력받은 수열, x는 두 수열의 합

메모리 128MB 

데이터의 개수가 1,000만 단위가 넘어가지 않도록...

 

1. itertools 라이브러리 사용해서 combination을 만들어서 x를 만드는 조합 개수를 찾자

-> 메모리 초과 (최대 10만 수열에서 2개 원소로 조합을 만들어서 리스트에 저장하면 대략 50억 가량의 데이터가 나옴....

from itertools import combinations
import sys
n = int(sys.stdin.readline().rstrip())
data = list(map(int, sys.stdin.readline().rstrip().split()))
x = int(sys.stdin.readline().rstrip())
data = list(combinations(data, 2))
cnt = 0
for i in data:
if sum(i) == x:
cnt += 1
print(cnt)

 

2. 메모리 초과나오니까 data의 개수를 최대한 줄여보자. 두 수를 더해도 x가 안되거나 x를 넘어가면 data에서 해당 원소를 빼자

-> 메모리 초과

from itertools import combinations
import sys
n = int(sys.stdin.readline().rstrip())
data = list(map(int, sys.stdin.readline().rstrip().split()))#최대 100만
data.sort()
x = int(sys.stdin.readline().rstrip())
#나름 data 개수 줄이기 위함....
if min(data) + max(data) < x:
data.remove(min(data))
elif max(data) > x:
data.remove(max(data))
data = list(combinations(data, 2)) #위에서 data가 제거되지 않으면 어차피 메모리 초과
cnt = 0
for i in data:
if sum(i) == x:
cnt += 1
print(cnt)

 

3. 조합을 없애고 이중 반복문으로 수열을 하나씩 더해보자

-> 시간 초과 (예상했음. O(N^2)이 될텐데 최대 N = 10만 ^ 2)

import sys
from collections import deque
n = int(sys.stdin.readline().rstrip())
data = list(map(int, sys.stdin.readline().rstrip().split()))
x = int(sys.stdin.readline().rstrip())
data.sort()
data = deque(data)
if min(data) + max(data) < x:
data.popleft()
elif max(data) > x:
data.pop()
cnt = 0
for i in range(len(data)):
for k in range(i+1, len(data)-1):
if data[i] + data[k+1] == x:
cnt += 1
print(cnt)

 

4. for문을 어떻게든 줄이려고 bisect 라이브러리 사용해서 x에 data에서 가장 작은 원소를 뺀 수가 data의 어느 자리에 들어갈 지 index 저장후 그 index를 마지막으로 두고 for문 돌림

-> 시간초과 (x= 2000000이고 data[0] = 1이면 소용없음)

import sys
from collections import deque
from bisect import bisect_right
n = int(sys.stdin.readline().rstrip())
data = list(map(int, sys.stdin.readline().rstrip().split()))
x = int(sys.stdin.readline().rstrip())
data.sort()
sub = x - data[0]
idx = bisect_right(data, sub)
#x와 data[0]이 같은 경우 idx=1, x가 data[0]보다 작을 경우 idx =0
cnt = 0
for i in range(idx+1):
if idx == 0 or idx == 1:
break
for k in range(i+1, len(data)-1):
if data[i] + data[k+1] == x:
cnt += 1
print(cnt)

 

5. 검색 후 투 포인터로 해결하는 거라고 알아냄. data를 정렬한 후 right와 left를 초기화. x보다 크면 right -= 1, 작으면 left += 1, x와 같으면 right -=1 또는 left +=1 하기

-> 많아야 O(n) + O(nlogn)복잡도가 나옴. ( O(nlogn) : sort())

import sys
n = int(sys.stdin.readline().rstrip())
data = list(map(int, sys.stdin.readline().rstrip().split()))
x = int(sys.stdin.readline().rstrip())
data.sort()
left = 0
right = len(data)-1
cnt = 0
while left < right:
if data[left] + data[right] < x:
left += 1
elif data[left] + data[right] > x:
right -= 1
elif data[left] + data[right] == x:
cnt += 1
right -= 1
print(cnt)

 

728x90

'알고리즘 > 백준' 카테고리의 다른 글

28014 자바  (0) 2024.04.09
11328 Strfry  (0) 2024.03.31
13300 방 배정  (0) 2024.03.31
1267 핸드폰 요금  (0) 2024.03.12
2309 일곱 난쟁이  (0) 2024.03.12
'알고리즘/백준' 카테고리의 다른 글
  • 11328 Strfry
  • 13300 방 배정
  • 1267 핸드폰 요금
  • 2309 일곱 난쟁이
hapBday
hapBday
hapBday
개발자로 성장하기 위한 기록들
hapBday
전체
오늘
어제
  • 분류 전체보기 (203)
    • CS (12)
      • 컴퓨터네트워크 (11)
      • 운영체제 (0)
      • 분산 시스템 (0)
      • 데이터베이스 (1)
    • Spring (47)
      • Spring 핵심 원리 (13)
      • Spring MVC (15)
      • Spring DB (12)
      • Spring Security (6)
    • JPA (14)
    • 알고리즘 (30)
      • 프로그래머스 (6)
      • 백준 (20)
    • Design Pattern (0)
    • 언어 (5)
      • JAVA (5)
    • ASAC 웹 풀스택 (38)
      • Spring Boot (21)
      • React (0)
      • DevOps (8)
    • 트러블슈팅 (15)
    • DevOps (5)
      • Docker (5)
    • ETC (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • 인프런
  • 백준
  • aws lambda
  • cookie
  • 김영한
  • Java
  • 3-layerd 아키텍쳐 패턴
  • currency control
  • jwt
  • x-lock
  • S3
  • 트랜잭션
  • Spring
  • CORS
  • spring security
  • multi-stage
  • s-lock
  • 구현
  • 티스토리챌린지
  • CSRF
  • JPA
  • spring boot
  • MVC
  • docker
  • docker best practices
  • basicerrorcontroller
  • docker workflow
  • 프로그래머스
  • 오블완
  • Session

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.3.0
hapBday
3273: 두 수의 합
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.