标签:int 整合 注意 com new java div ret 记录
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 首先想到的办法就是将两个数组整合成一个有序数组,这样通过数组的顺序很容易的找到Median数,注意此时两个数组都是有序数组,整合的时候可以优化时间,具体看代码(时间不够啦,草草记录了一下)!!!
效率不过很低,还有一次没有accept过,下次找时间更新优化后的代码测试。
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int count=nums1.length+nums2.length; int[] nums=new int[count]; int i=0; int j=0; int k=0; while(k<count){ if(i<nums1.length&&j<nums2.length){ if(nums1[i]<nums2[j]){ nums[k]=nums1[i]; i++; } else{ nums[k]=nums2[j]; j++; } } else if(i>=nums1.length){ nums[k]=nums2[j]; j++; } else{ nums[k]=nums1[i]; i++; } k++; } if(count%2==1){ return nums[count/2]; } else{ return (nums[count/2-1]+nums[count/2])/2.0; } } }
标签:int 整合 注意 com new java div ret 记录
原文地址:http://www.cnblogs.com/guoluo20170216/p/6492924.html