티스토리 뷰
Memory Usage: 14.6 MB
Given an array, arr, of positive integers sorted in a strictly increasing order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
- 1 <= arr.length <= 1000
- 1 <= arr[i] <= 1000
- 1 <= k <= 1000
- arr[i] < arr[j]for1 <= i < j <= arr.length
문제 설명
오름차 순으로 정렬된 양의 정수가 저장된 array인 arr와 정수 k가 주어진다.
array에서 빠진 수들 중 K번째 양의 정수를 찾는 문제이다.
Example 1을 보면 arr에서 빠진 수는, [1, 4, 5, 8, 9, 10, 12, 13, ...] 이므로, 5번째 수는 9이다.
Example 2를 보면 arr에 빠진 수는 [5, 6, 7, ... ] 이므로, 2번째 수는 6이다.
arr의 길이가 1000까지, arr에 들어갈 수 있는 수에는 1000을 포함한다.
k의 수는 1000까지 가능하므로, 최대 2000의 수까지 저장한다.
ex. arr에 1부터 1000까지 들어가며, k로 1000번째 수를 요구하는 경우, 그 값은 2000이다.
문제 풀이
두 가지 방법으로 문제를 풀었다.
range 특성상 입력된 값은 미포함하므로, +1을 한다.
1. set으로 만들고, 여집합 연산을 수행하여 k 번째 값 구하기.
k가 1000일 때를 고려하여 다 집어 넣고, 차집합을 구한다.
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
s = set([i for i in range(arr[-1] + 1001)])
a = list(s - set(arr))
return a[k]
84 / 84 test cases passed.
Status: Accepted
Runtime: 56 ms
Memory Usage: 14.6 MB
2. for문을 돌려가며, 1씩 수를 증가시켜 arr에 포함여부를 판단. 미포함한다면 list에 넣기.
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
answer = []
for i in range(arr[-1]+1001):
if i not in arr:
answer.append(i)
return answer[k]
84 / 84 test cases passed.
Status: Accepted
Runtime: 292 ms
Memory Usage:14.6 MB
'코딩테스트 > leetcode' 카테고리의 다른 글
118. Pascal's Triangle 파스칼의 삼각형 (0) | 2022.10.17 |
---|---|
[leetcode][python] Merge Sorted Array (0) | 2021.01.13 |
[프로그래머스][python] 더 맵게 (0) | 2021.01.12 |
[leetcode][python] Check If Two String Arrays are Equivalent (0) | 2021.01.10 |
[프로그래머스][python] K번째 수 (삽입정렬) + 다른 사람들의 풀이 (0) | 2020.08.31 |
- Total
- Today
- Yesterday
- Tistory
- map
- flask
- 에러로그
- 스프링 #시큐리티 #에러
- MySQL
- dumps
- 정렬
- 프로그래머스
- C++
- Python
- python #프로그래머스 #완전탐색
- python #leetcode #set
- python #프로그래머스 #알고리즘
- bfs #백준 #2606 #python
- 알고리즘
- python #leetcode #algorithm
- notion
- 프로그래머스 #heap #힙 #heapq #python
- 파이썬
- 선택정렬
- leetcode #python #알고리즘
- centOS7
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |