-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path066_Kth Element of Two Sorted Arrays.cpp
81 lines (63 loc) · 1.5 KB
/
066_Kth Element of Two Sorted Arrays.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Time Complexity -> O(n)
Space Cmplexity -> O(1)
int ninjaAndLadoos(vector<int> &row1, vector<int> &row2, int m, int n, int k) {
// Write your code here.
int i = 0, j = 0;
int ans = -1;
while(i < m and j < n and k > 0)
{
if(row1[i] <= row2[j])
{
ans = row1[i];
++i;
}
else
{
ans = row2[j];
++j;
}
--k;
}
while(i < m and k > 0)
{
ans = row1[i++];
--k;
}
while(j < n and k > 0)
{
ans = row2[j++];
--k;
}
return ans;
}
// Time Complexity -> O(min(log(n), log(m)) )
// Space Cmplexity -> O(1)
#include<bits/stdc++.h>
int ninjaAndLadoos(vector<int> &row1, vector<int> &row2, int n, int m, int k) {
// Write your code here.
if(n > m)
return ninjaAndLadoos(row2, row1, m, n, k);
int low = max(0,k - m), high = min(k, n);
while(low <= high)
{
int cut1 = (low + high) >> 1;
int cut2 = k - cut1;
int left = (cut1 == 0 ? INT_MIN : row1[cut1-1]);
int left2 = (cut2 == 0 ? INT_MIN: row2[cut2-1]);
int right = (cut1 == n ? INT_MAX : row1[cut1]);
int right2 = (cut2 == m ? INT_MAX : row2[cut2]);
if(left <= right2 and left2 <= right)
{
return max(left, left2);
}
else if(left >= right2)
{
high = cut1-1;
}
else
{
low = cut1+1;
}
}
return 1;
}