Skip to content

LeetCode: 1539-Kth Missing Positive Number 解題紀錄

Last Updated on 2023-03-06 by Clay

題目

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: 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] for 1 <= i < j <= arr.length

Follow up:

Could you solve this problem in less than O(n) complexity?


題目指定我們要找到第 k 個不存在於陣列 arr正整數,並將其回傳。要注意的是,第 k 個正整數的值可能會遠超過陣列 arr 的範圍。


解題思路

這題不愧是 Easy 題,直接從 1 開始計數就能獲得不錯的跑分結果。

簡單來說,就是我們設定一個 missing 的變數,一開始初始化為 1;接著我們逐項與 arr 中的值做比較。

  • 如果與 arr 中的值一致,則將 missing 加 1
  • 如果與 arr 中的值不一致,則除了將 missing 加 1 外,也要把 k 減去 1;一但 k 減至 0,則將當前的 missing 回傳,因為它就是第 k 個遺失的正整數

值得注意的是,可能整個 arr 走完都還沒找到第 k 個正整數,這時候只要透過 k 剩下的值,我們便能直接計算出最後要的正整數。


複雜度

Time ComplexityO(n)
Space ComplexityO(1)


C++ 範例程式碼

class Solution {
public:
    int findKthPositive(vector<int>& arr, int k) {
        // Init
        int missing = 1;

        // Comparing with the `arr` one by one
        for (int i=0; i<arr.size(); ++i) {
            // If `missing` not in `arr`, that means we can count down `k` value
            while (missing != arr[i]) {
                --k;
                if (k == 0) {
                    return missing;
                }
                ++missing;
            }
            ++missing;
        }

        // If `arr` is over and we do not find the answer, we can calculate the results directly
        return missing + k - 1;
    }
};



Python 範例程式碼

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        # Init
        missing = 1

        # Comparing with the `arr` one by one
        for num in arr:
            # If `missing` not in `arr`, that means we can count down `k` value
            while missing != num:
                if k == 1:
                    return missing

                k -= 1
                missing += 1
            missing += 1

        # If `arr` is over and we do not find the answer, we can calculate the results directly
        return missing + k - 1

References


Read More

Leave a Reply