File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int findKthPositive (int [] a , int k )
3
+ {
4
+ int B [] = new int [a .length ];
5
+
6
+ //equation (A)
7
+ //B[i]=a[i]-i-1
8
+
9
+
10
+ //B[i]=number of missing numbers BEFORE a[i]
11
+ for (int i =0 ;i <a .length ;i ++)
12
+ B [i ]=a [i ]-i -1 ; //-1 is done as here missing numbers start from 1 and not 0
13
+
14
+ //binary search upper bound of k
15
+ //smallest value>=k
16
+
17
+ int lo =0 ,hi =B .length -1 ;
18
+
19
+ while (lo <=hi )
20
+ {
21
+ int mid = lo +(hi -lo )/2 ;
22
+
23
+ if (B [mid ]>=k )
24
+ hi =mid -1 ;
25
+ else
26
+ lo =mid +1 ;
27
+ }
28
+
29
+ //lo is the answer
30
+
31
+ /*now the number to return is a[lo]-(B[lo]-k+1) (EQUATION B)
32
+ //where (B[lo]-k+1) is the number of steps we need to go back
33
+ //from lo to retrieve kth missing number, since we need to find
34
+ //the kth missing number BEFORE a[lo], we do +1 here as
35
+ //a[lo] is not a missing number when B[lo]==k
36
+ //putting lo in equation(A) above
37
+ //B[i]=a[i]-i-1
38
+ //B[lo]=a[lo]-lo-1
39
+ and using this value of B[lo] in equation B
40
+ //we return a[lo]-(a[lo]-lo-1-k+1)
41
+ we get lo+k as ans
42
+ so return it*/
43
+
44
+ return lo +k ;
45
+
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments