题目来源:
leetcode题目,网址:1539. 第 k 个缺失的正整数 - 力扣(LeetCode)
解题思路:
遍历数组的同时对缺失的正整数计数,返回第 k 个缺失的正整数即可。
解题代码:
class Solution {
public int findKthPositive(int[] arr, int k) {
int count=0;
int order=1;
for(int num:arr){
if(num!=order){
int temp=count+num-order;
if(temp>=k){
return order+k-count-1;
}
count=temp;
}
order=num+1;
}
return arr[arr.length-1]+k-count;
}
}
总结:
写代码时注意边界条件即可。
官方题解给出了两种解法。第一种是枚举。第二种是二分,对于数组中的某个元素,可以根据其所在位置和元素值,直接得到缺失元素个数。