第 k 个缺失的正整数
难度:
标签:
题目描述
代码结果
运行时间: 18 ms, 内存: 16.1 MB
/*
* 思路:
* 使用流操作计算数组中每个数字的缺失数字数量,
* 并在其中找到第 k 个缺失的数字。
*/
import java.util.Arrays;
public class Solution {
public int findKthPositive(int[] arr, int k) {
return Arrays.stream(arr)
.boxed()
.reduce(0, (missing, current) -> {
int expected = missing + 1;
if (expected < current) {
int missingCount = current - expected;
if (k <= missingCount) {
return missing + k;
}
k -= missingCount;
}
return current;
}, (a, b) -> a) + k;
}
}
解释
方法:
该题解采用了一种逐个检查的方法。首先,通过设置一个外部计数器 count 来遍历所有自然数,然后与数组 arr 中的元素进行比较。如果当前的 count 值不在 arr 中,即认为这是一个缺失的正整数,此时增加缺失计数器 n。一旦 n 达到 k,即找到了第 k 个缺失的正整数。如果整个数组都遍历完毕,但是缺失的数还没找完,就继续增加 count,直到找到第 k 个缺失的正整数。
时间复杂度:
O(k + n)
空间复杂度:
O(1)
代码细节讲解
🦆
在遍历数组时,你是如何处理数组中连续多个数字缺失的情况,比如在数组 [2, 5] 中找第 3 个缺失的正整数?
▷🦆
如果输入的数组 arr 中的最大数字非常接近 1000,而 k 还很大,比如 k = 100,你的方法是否还是有效?是否存在性能优化的可能?
▷🦆
为什么在遍历完数组后,还需要一个额外的 while 循环来继续寻找缺失的正整数?
▷🦆
你的解法在数组元素非常稠密,比如 arr = [1,2,3,...,999],且 k = 1 的情况下性能如何?
▷