【leetcode】4. Median of Two Sorted Arrays

来源:互联网 发布:沭阳网络问政12345 编辑:程序博客网 时间:2024/06/08 08:42
/** * 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 * */class Solution {public double findMedianSortedArrays(int[] nums1, int[] nums2) {int length1 = nums1.length;int length2 = nums2.length;int length = length1 + length2;int mid = (length) / 2;// 合并数组int[] nums = new int[length];double d = 0.0;if (length1 == 0) {if (length2 != 0) {nums = nums2;} else {return d;}} else {if (length2 != 0) {int i = 0, j = 0, k = 0;while (i < length1 && j < length2)if (nums1[i] <= nums2[j]) {nums[k++] = nums1[i++];} else {nums[k++] = nums2[j++];}while (i < length1)nums[k++] = nums1[i++];while (j < length2)nums[k++] = nums2[j++];} else {nums = nums1;}}// 奇偶性boolean even = length % 2 == 0 ? true : false;if (length > 0) {if (even) {d = (double) (nums[mid - 1] + nums[mid]) / 2;} else {d = nums[mid];}}return d;}}

思路:先判断各自的长度、最终的奇偶性,然后归并,最后找到中间的值



原创粉丝点击