Friday, January 8, 2021

Median of Two Sorted Arrays

 Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Follow up: The overall run time complexity should be O(log (m+n)).

 

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000

Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000

Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000

 

Constraints:

  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -106 <= nums1[i], nums2[i] <= 106
Solution:


public class MedianOfSortedArraysSolution {

	public static void main(String[] args) {

		int ar1[] = { 1, 2 }; // { 2, 3, 5, 8, 23 }; // { -5, 3, 6, 12, 15 };
		int ar2[] = { 3, 4 }; // { 10, 12, 14, 16, 18, 20 }; // { -12, -10, -6, -3, 4, 10 };

		int ar3[] = mergeSortedArrays(ar1, ar2);

		if (ar3.length % 2 == 1) {
			System.out.print((double) ar3[ar3.length / 2]);
		} else {
			System.out.print((double) (ar3[(ar3.length - 1) / 2] + ar3[(ar3.length + 1) / 2]) / 2);
		}
	}

	private static int[] mergeSortedArrays(int[] ar1, int[] ar2) {

		int n = 0;
		int m = 0;
		int l = 0;
		int ar3[] = new int[ar1.length + ar2.length];

		while (n < ar1.length || m < ar2.length) {

			if (n == ar1.length || (m != ar2.length && ar1[n] > ar2[m])) {
				ar3[l] = ar2[m];
				m++;
			} else {
				ar3[l] = ar1[n];
				n++;
			}
			l++;
		}

		return ar3;
	}

}

Thanks for reading :) 

Whether this post is helpful?

Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments. feedback are welcome...

No comments:

Post a Comment

Valid Parentheses

  Given a string   s   containing just the characters   '(' ,   ')' ,   '{' ,   '}' ,   '['   and   ...