题目描述

​题目链接:1539. 第 k 个缺失的正整数​

数据结构与算法【LeetCode-Offer】:1.2数组—1539.第 k 个缺失的正整数_System

解题思路

数据结构与算法【LeetCode-Offer】:1.2数组—1539.第 k 个缺失的正整数_i++_02


数据结构与算法【LeetCode-Offer】:1.2数组—1539.第 k 个缺失的正整数_i++_03

代码演示

package com.kami.leetcode.arrayStudy;

/**
* @Description: TODO
* @author: scott
* @date: 2021年11月30日 9:18
*/
public class L_1539 {
public static int findKthPositive(int[] arr, int k){
int cur = 1;

int i = 0;
while (i < arr.length){
if(cur != arr[i]){
//cur缺失
k--;
if(k == 0){
return cur;
}
cur++;
}else {
i++;
cur++;
}
}

// 遍历完数组但是 k 还没有减完
return (cur - 1) + k;
}

public static void main(String[] args) {
int[] arr = new int[]{1, 3, 4, 6};
int k = 2;
int kthPositive = findKthPositive(arr, k);
System.out.println(kthPositive);
}
}