Created
July 10, 2017 20:25
-
-
Save kriznaraj/3687771a9703eb916d048175850f76e9 to your computer and use it in GitHub Desktop.
K-th Element of Two Sorted Arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| namespace prob | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| //Test input | |
| var x = Find( | |
| new int[] { 1, 2, 10, 24, 36, 46, 47, 48, 49, 50 }, | |
| 0, | |
| 9, | |
| new int[] { 2, 2, 2, 3, 4, 6, 10, 20 }, | |
| 0, | |
| 7, | |
| 7); | |
| Console.WriteLine(x); | |
| } | |
| static int up(int s, int e, int len) | |
| { | |
| return (s + Math.Abs(e-s) / 2)%len; | |
| } | |
| static int Find(int[] a, int s1, int e1, int[] b, int s2, int e2, int k) | |
| { | |
| var m = up(s1, e1, a.Length); | |
| var n = up(s2, e2, b.Length); | |
| if(s1 == e1) | |
| return b[n]; | |
| if(s2==e2) | |
| return a[m]; | |
| var t = m+n+2; //as the index starts from 0 | |
| if (t > k) | |
| { | |
| if (a[m] > b[n]) | |
| { | |
| return Find(a, s1, m, b, s2, e2, k); | |
| } | |
| else | |
| { | |
| return Find(a, s1, e1, b, s2, n, k); | |
| } | |
| } | |
| else | |
| { | |
| if (a[m] < b[n]) | |
| { | |
| return Find(a, m + 1, e1, b, s2, e2, k); | |
| } | |
| else | |
| { | |
| return Find(a, s1, e1, b, n+1, e2, k); | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment