给一个严格升序数组,一个整数k
返回数组缺失的第k个正数。
思路:
因为都是正数,而且是排好序的,
其中的正整数应该是从1 到 数组中的最大值 这个范围,
遍历1 到 数组的最大值,中间不在数组中的数字就是缺失的。
另外,k可能超出数组最大值的范围,那么超出的部分只需要用最大值+k-现在的次数。
class Solution {
public int findKthPositive(int[] arr, int k) {
int n = arr.length;
int maxNum = arr[n-1];
int cnt = 0;
int res = 1;
int idx = 0;
while(res < maxNum) {
while(res != arr[idx]) { //这里可能已经等于最大值
cnt ++;
if(cnt == k) return res;
res ++;
}
idx ++; //上面已经等于最大值时idx会越界,但是不影响,因为会跳出循环
res ++; //上面已经等于最大值时res会超过最大值
}
return maxNum+(k-cnt);
}
}