LeetCode-java实现-T4Median of Two Sorted Arrays

来源:互联网 发布:cydia怎么卸载软件 编辑:程序博客网 时间:2024/06/06 12:24
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)).

注意:这里要注意的是当m+n是偶数是,返回的是中间两个数求和除以2.0的结果,奇数就是返回中间值。
这里采用的是增加一个辅助空间的方式。
package org.algorithm.leetcode;public class Item4 {public static double findMedianSortedArrays(int[] nums1, int[] nums2) {int length1 = nums1.length;int length2 = nums2.length;int medianLength = (length1 + length2)/2;if(length1 == 0 || nums1 == null)if((length1 + length2)%2 == 0)return (nums2[medianLength-1]+nums2[medianLength])/2.0;elsereturn nums2[medianLength];else if(length2 == 0 || nums2 == null)if((length1 + length2)%2 == 0)return (nums1[medianLength-1]+nums1[medianLength])/2.0;elsereturn nums1[medianLength];int[] array = new int[length1 + length2];int i = 0;int j = 0;int k = 0;while(i < length1 && j < length2) {if(nums1[i] <= nums2[j])array[k++] = nums1[i++];elsearray[k++] = nums2[j++];}while(i == length1 && j <length2)array[k++] = nums2[j++];while(j == length2 && i < length1)array[k++] = nums1[i++];if((length1 + length2)%2 == 0)return (array[medianLength-1]+array[medianLength])/2.0;elsereturn array[medianLength];    }public static void main(String[] args) {int nums1[] = {};int nums2[] = {2,3};System.out.println(findMedianSortedArrays(nums1,nums2));}}

0 0
原创粉丝点击