1539. Kth Missing Positive Number
作者:互联网
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; } }
标签:arr,return,int,Positive,Number,else,Kth,diff,mid 来源: https://www.cnblogs.com/feiflytech/p/16163633.html