carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1539:第 k 个缺失的正整数(kth-missing-positive-number) #242

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个 严格升序排列 的正整数数组 arr 和一个整数 k 。

请你找到这个数组里第 k 个缺失的正整数。

示例 1:

输入:arr = [2,3,4,7,11], k = 5 输出:9 解释:缺失的正整数包括 [1,5,6,8,9,10,12,13,...] 。第 5 个缺失的正整数为 9 。

示例 2:

输入:arr = [1,2,3,4], k = 2 输出:6 解释:缺失的正整数包括 [5,6,7,...] 。第 2 个缺失的正整数为 6 。  

提示:

1 <= arr.length <= 1000 1 <= arr[i] <= 1000 1 <= k <= 1000 对于所有 1 <= i < j <= arr.length 的 i 和 j 满足 arr[i] < arr[j] 

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/kth-missing-positive-number

carloscn commented 1 year ago

code

pub fn find_kth_positive(arr: Vec<i32>, k: i32) -> i32
{
    if arr.is_empty() {
        return 0;
    }

    let mut ret:i32 = 0;
    let mut j:usize = 0;
    let mut s:usize = 0;

    let mut ab:Vec<i32> = vec![];

    for i in 0..i32::MAX {
        if !arr.contains(&i) {
            ab.push(i);
            if ab.len() > k as usize {
                return ab.pop().unwrap();
            }
        }
    }

    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/554922 https://github.com/carloscn/structstudy/commit/d9f2d107d1bde359aba3a20c460bf4324c6dae0a