My first binary search solution:

class Solution {
    public int findKthPositive(int[] arr, int k) {
        int l=0, r = arr.length-1;
        while(l+1<r){
            int mid = (l+r)/2;
            if(arr[mid]-mid-1>=k)
                r=mid;
            else
                l=mid;
        }
        if(arr[l]-l-1>=k){
            int diff = (arr[l]-l)-k;
            return arr[l]-diff;
        }else if (arr[r]-r-1>=k){
            int diff = (arr[r]-r)-k;
            return arr[r]-diff;
        }
        else{
            int diff = k-(arr[r]-r-1);
            return arr[r]+diff;
        }
    }
}

My second binary search solution:

class Solution {
    public int findKthPositive(int[] arr, int k) {
        int l=0, r = arr.length-1;
        while(l+1<r){
            int mid = (l+r)/2;
            if(arr[mid]-mid-1>=k)
                r=mid;
            else
                l=mid;
        }
        if(arr[l]-l-1>=k){return l+k;
        }else if (arr[r]-r-1>=k){
            return r+k;
        }
        else{
            return r+k+1;
        }
    }
}

A simple O(n) solution:

class Solution {
    public int findKthPositive(int[] arr, int k) {
        for(int i: arr){
            if(i<=k)
                k++;
            else
                break;
        }
        return k;
    }
}

 

posted on 2022-04-19 06:53  阳光明媚的菲越  阅读(16)  评论(0编辑  收藏  举报