In the Leetcode Median of Two Sorted Arrays problem solution in C# programming Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Leetcode Median of Two Sorted Arrays problem solution in C# programming
public class Solution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums = new int[nums1.Length + nums2.Length];
int i = 0, j = 0, k = 0;
while (i < nums1.Length && j < nums2.Length) {
if (nums1[i] < nums2[j]) {
nums[k++] = nums1[i++];
}
else
{
nums[k++] = nums2[j++];
}
}
if (i < nums1.Length) {
while ( i < nums1.Length) {
nums[k++] = nums1[i++];
}
}
else if (j < nums2.Length) {
while (j < nums2.Length) {
nums[k++] = nums2[j++];
}
}
if (nums.Length %2 == 0)
{
int mid = nums.Length / 2;
double r = (double) nums[mid];
double l = (double) nums[mid -1];
return (l + r) /2;
}
else
{
return nums[nums.Length /2];
}
}
}
Also read,
- Leetcode Median of Two Sorted Arrays problem solution in C
- Leetcode Median of Two Sorted Arrays problem solution in C++
- Leetcode Median of Two Sorted Arrays problem solution in Java
- Leetcode Median of Two Sorted Arrays problem solution in Python