本文共 991 字,大约阅读时间需要 3 分钟。
为了解决这个问题,我们需要找到缺失在给定数组中的第k个正整数。数组中的数是严格递增的正整数,但可能存在缺失的数,我们需要找到这些缺失数中的第k个。
我们可以使用两个变量来跟踪当前位置和缺失的数量。具体步骤如下:
count和cur,分别用于记录缺失的数量和当前位置。这种方法确保了我们能够高效地找到第k个缺失的数,避免了不必要的重复计算。
#includeusing namespace std;int findKthPositive(vector & arr, int k) { int count = 0; int cur = 0; for (int num : arr) { cur++; while (cur < num) { count++; if (count == k) { return cur; } cur++; } } while (count < k) { cur++; count++; if (count == k) { return cur; } } return -1; // This line is theoretically unreachable as per problem constraints}
count用于记录缺失的数量,cur用于跟踪当前位置。cur,然后检查是否存在缺失的数。如果发现缺失的数,继续检查直到找到第k个缺失的数。这种方法确保了我们能够高效地找到第k个缺失的数,避免了不必要的重复计算。
转载地址:http://saqo.baihongyu.com/