LeetCode-Median of Two Sorted Arrays

Description:
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

题意:有两个已排序的整数类型的数组,要求出两个数组合并后有序数组的中位数;

解法:因为两个数组已经是有序的了,将两个数组合并的时间复杂度就是O(m+n);合并后求中位数就非常简单了;

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int nums[] = new int[nums1.length + nums2.length +1];
        int i = 0, j = 0;//数组1、数组2的下标
        int len = 0;//两数组合并后的长度
        while(i < nums1.length || j < nums2.length){
            int x = i < nums1.length ? nums1[i] : Integer.MAX_VALUE;
            int y = j < nums2.length ? nums2[j] : Integer.MAX_VALUE;
            if(x < y) {nums[len++] = x; i++;}
            else      {nums[len++] = y; j++;}
        }
        if(len % 2 == 0){
            return (nums[len / 2 - 1] + nums[len / 2]) / 2.0;
        }
        else{
            return nums[len / 2];
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80926489