4. 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

分析:合併兩個列表求中位數即可。

Java

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int i = 0, j = 0;
        double ans = 0;
        int[] nums = new int[10000];
        while(i<nums1.length && j<nums2.length){
            if(nums1[i] < nums2[j]){
                nums[i+j] = nums1[i++];
            }
            else{
                nums[i+j] = nums2[j++];
            }
        }
        while(i<nums1.length){
            nums[i+j] = nums1[i++];
        }
        while(j<nums2.length){
            nums[i+j] = nums2[j++];
        }
        int n = i + j;
        if(n%2 == 0){
            ans = (double)(nums[n/2] + nums[n/2-1])/2;
        }
        else{
            ans = nums[n/2];
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章