Created
June 6, 2017 13:23
-
-
Save xynophon/fa266de95b74516bf4f30513afc2518e to your computer and use it in GitHub Desktop.
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
| public class MedianofTwoSortedArrays { | |
| public double findMedianSortedArrays(int[] nums1, int[] nums2) { | |
| int[] merged = new int[nums1.length + nums2.length]; | |
| int i = 0; | |
| int j = 0; | |
| int k = 0; | |
| int target_index = (nums1.length + nums2.length)/2; | |
| while(i <= target_index){ | |
| if (j < nums1.length && k < nums2.length) { | |
| merged[i++] = nums1[j] < nums2[k] ? nums1[j++] : nums2[k++]; | |
| }else if (j < nums1.length){ | |
| merged[i++] = nums1[j++]; | |
| }else { | |
| merged[i++] = nums2[k++]; | |
| } | |
| } | |
| if((nums1.length + nums2.length)%2 == 1) { | |
| return (double) merged[target_index]; | |
| }else { | |
| return (double) (merged[target_index] + merged[target_index-1])/2; | |
| } | |
| } | |
| public static void main(String[] args){ | |
| int[] arr1 = {1, 2, 3, 4, 5}; | |
| int[] arr2 = {6, 7, 8, 9, 10}; | |
| MedianofTwoSortedArrays mtsa = new MedianofTwoSortedArrays(); | |
| System.out.println(mtsa.findMedianSortedArrays(arr1, arr2)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment