Home LeetCode. 4 Median of Two Sorted Arrays
Post
Cancel

LeetCode. 4 Median of Two Sorted Arrays

image

[Link] https://leetcode.com/problems/median-of-two-sorted-arrays/


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
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len = nums1.length + nums2.length;
        int[] merged = new int[len];
        int index1 = 0, index2 = 0;
        for(int i = 0; i < len; i++) {
            if(index1 < nums1.length && index2 < nums2.length) {
                if(nums1[index1] > nums2[index2]) merged[i] = nums2[index2++];
                else merged[i] = nums1[index1++];
            } else if(index1 < nums1.length) {
                for(int j = i; j < len; j++) {
                    merged[j] = nums1[index1++];
                }
                break;
            } else if(index2 < nums2.length) {
                for(int j = i; j < len; j++) {
                    merged[j] = nums2[index2++];
                }
                break;
            }
        }
        if(len%2 == 0) {
            return (double)(merged[(len-1)/2] + merged[len/2])/2;
        } else return merged[(len-1)/2];
    }
}
This post is licensed under CC BY 4.0 by the author.