LeetCode第四题Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

对时间复杂度有要求,就不能直接新建数组,然后拼接nums1和nums2到新数组然后用快排,思路是拼接新数组的时候直接排好序。

class Solution {
      public  double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length = nums1.length+nums2.length;
        if (length==0){
            return 0;
        }
        int[] result = new int[length];
        int i=0;int j =0;
        int n = 0;
        while (n<length){
            if (i>=nums1.length){//如nums[1]和nums[2]其中一个已经拼接完,则将剩余的数组直接拼接
                for (int i1=n;i1<length;i1++){
                    result[i1] = nums2[j];
                    j++;
                }
                break;
            }
            if (j>=nums2.length){
                for (int i1=n;i1<length;i1++){
                    result[i1] = nums1[i];
                    i++;
                }
                break;
            }
            if (nums1[i]<=nums2[j]){//将当前的nums[1]和nums[2]的数字进行比较,将较小的数字拼接到新数组中
                result[n]=nums1[i];
                i++;
                n++;

            }
            else {
                result[n] = nums2[j];
                j++;
                n++;
            }
        }
        if (length==1){
             return result[0];
        }
        if (length%2==0){
                        return ((double) result[(length-1)/2]+(double) result[(length-1)/2+1])/2;
        }
        else {
            return result[length/2];
        }

    }
}
发布了43 篇原创文章 · 获赞 1 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章