본문 바로가기
python-algorithm

leetcode 1539. Kth Missing Positive Number

by 무적김두칠 2023. 3. 6.

https://leetcode.com/problems/kth-missing-positive-number/description/

 

Kth Missing Positive Number - LeetCode

Can you solve this real interview question? Kth Missing Positive Number - Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Return the kth positive integer that is missing from this array.   Example 1: Input:

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def findKthPositive(self, arr: List[int], k: int-> int:
            answer = []
            number = 1
            while True:
                if len(answer) == k:
                    return answer[-1]
                if number in arr:
                    pass
                else:
                    answer.append(number)
                number += 1
cs

정말 문제 그대로 구현하긴 했으나 'in' 함수 자체가 시간복잡도가 O(N) 점을 감안하면 최고의 풀이법은 아님

max 함수를 써서 max(arr) 과 k 만큼의 차이와 len(arr) 를 비교하면서 여러 조건문으로 분기하면 시간복잡도는 떨어뜨릴수 있을것으로 보임

I really implemented the problem as it is, but considering that the 'in' function itself has O(N) time complexity, it's not the 
best solution.

It seems that the time complexity can be reduced by using the max function to branch into several conditional statements while comparing the difference between max(arr) and k and len(arr)

반응형

댓글