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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章