GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/java/1539_Kth_Missing_Positive_Number.java at master · iamsathish/leetcode Expand file tree/ Copy path1539_Kth_Missing_Positive_Number.javaMore file actions 43 lines (36 loc) · 1.28 KB / Copy path1539_Kth_Missing_Positive_Number.javaFile metadata and controls43 lines (36 loc) · 1.28 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 class Solution { public int findKthPositive(int[] a, int k) { int B[] = new int[a.length]; // equation (A) // B[i]=a[i]-i-1 // B[i]=number of missing numbers BEFORE a[i] for (int i = 0; i < a.length; i++) B[i] = a[i] - i - 1; // -1 is done as here missing numbers start from 1 and not 0 // binary search upper bound of k // smallest value>=k int lo = 0, hi = B.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (B[mid] >= k) hi = mid - 1; else lo = mid + 1; } // lo is the answer /* * now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B) * where (B[lo]-k+1) is the number of steps we need to go back * from lo to retrieve kth missing number, since we need to find * the kth missing number BEFORE a[lo], we do +1 here as * a[lo] is not a missing number when B[lo]==k * putting lo in equation(A) above * B[i]=a[i]-i-1 * B[lo]=a[lo]-lo-1 * and using this value of B[lo] in equation B * we return a[lo]-(a[lo]-lo-1-k+1) * we get lo+k as ans * so return it */ return lo + k; } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |