My Java solution, easy to understand


  • -1
    D

    public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int i=0, j=0, len1=0, len2=0;
    if (nums1!=null) {
    len1 = nums1.length;
    }
    if (nums2 != null) {
    len2 = nums2.length;
    }
    int[] arr = new int[len1+len2];
    int cur = 0;
    while (i<len1 && j<len2) {
    if (nums1[i]<=nums2[j]) {
    arr[cur++]=nums1[i++];
    } else {
    arr[cur++]=nums2[j++];
    }
    }
    while (i<len1) {
    arr[cur++]=nums1[i++];
    }
    while (j<len2) {
    arr[cur++]=nums2[j++];
    }
    double res;
    if ((len1+len2) % 2 != 0) {
    res = (double)arr[(len1+len2)/2];
    } else {
    int sumLen = len1 + len2;
    res = ((double)arr[sumLen/2-1] + (double)arr[sumLen/2])/2.0;
    }
    return res;
    }
    }


  • 0
    S

    @douglas__ please correct the indentation. very difficult to read :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.