标签:
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)).
题目很简单,比较两数组当前指针指向的值,选择小的添加到新数组,找出中间值。注意各种情况都要考虑周全,否则很容易出现数组越界(就是这个原因磨蹭了好久)。
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m=nums1.length; int n=nums2.length; int a=(m+n)/2; int b=(m+n)%2; if(m==0){ if(n==0) return 0.0; else if(b==0) return ((double)nums2[a-1]+(double)nums2[a])/2; else return (double)nums2[a]; } if(n==0){ if(b==0) return ((double)nums1[a-1]+(double)nums1[a])/2; else return (double)nums1[a]; } int j=0,k=0; int nums3[]=new int[a+1]; for(int i=0;i<=a;i++){ if(j>=m){ nums3[i]=nums2[k]; k++; }else if(k>=n){ nums3[i]=nums1[j]; j++; }else if(nums1[j]<=nums2[k]){ nums3[i]=nums1[j]; j++; }else{ nums3[i]=nums2[k]; k++; } } if(b==0){ return ((double)nums3[a-1]+(double)nums3[a])/2; }else{ return (double)nums3[a]; } } }
LeetCode 4 Median of Two Sorted Arrays
标签:
原文地址:http://www.cnblogs.com/gonewithgt/p/4570169.html