LeetCode.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)).

You may assume nums1 and nums2 cannot be both empty.

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

思路:最简单的思路,合并之后找中值,这里需要注意时间复杂度,不能超时。
合并方法如下:
先创建一个新数组,此数组的大小大于或者等于两个已知数组大小的和。通过比较两个有序数组中的元素,谁小就把谁放到空数组,直到其中一个数组为空,最后把剩下的数组全部放到创建的数组里

代码如下:

package com.wanghao;

public class MedianofTwoSortedArrays {

	public static void main(String[] args) {
		int a[] = {1,3} ;
	    int b[] = {2};
	    System.out.println(findMedianSortedArrays(a, b));

	}

	static double findMedianSortedArrays(int[] nums1, int[] nums2) {
		int index1 = 0, index2 = 0, index3 = 0;
		int size = nums1.length + nums2.length;
		int[] combine = new int[size];
		while (index1 < nums1.length && index2 < nums2.length) {
			if (nums1[index1] < nums2[index2]) {
				combine[index3++] = nums1[index1++];
			} else {
				combine[index3++] = nums2[index2++];
			}
		}
		while (index1 < nums1.length) {
			combine[index3++] = nums1[index1++];
		}
		while (index2 < nums2.length) {
			combine[index3++] = nums2[index2++];
		}

		if (size % 2 == 1) {
			return combine[size / 2] * 1.0;
		} else {
			return (combine[size / 2] * 1.0 + combine[size / 2 -1] * 1.0)/2;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_32350719/article/details/88798399