【Shawn-LeetCode】4.Median of Two Sorted Arrays

版权声明:本文为博主原创文章,如有转载或提问请私信 https://blog.csdn.net/ShancoFolia/article/details/72866784

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

Subscribe to see which companies asked this question.


题目是很简单,但是如果把复杂度控制在log(m+n)的范围内,肯定是有问题的,先贴一个超时的算法

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums3=new int[nums1.length+nums2.length];
		System.arraycopy(nums1,0, nums3, 0, nums1.length);
		System.arraycopy(nums2,0, nums3, nums1.length, nums2.length);
		System.out.println(Arrays.toString(nums3));
		Arrays.sort(nums3);
		if(nums3.length%2==0){
			return (nums3[nums3.length/2-1]+nums3[nums3.length/2])/2.0;
		}
		else return nums3[nums3.length/2];
    }
}

正在探索新的方法



猜你喜欢

转载自blog.csdn.net/ShancoFolia/article/details/72866784
今日推荐