leetecode 上的一道题: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)).
实现代码:
package leetcode;
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int total = nums1.length+nums2.length;
int median;
int p=0,p1=0,p2=0;
int temp[]=new int[total];
boolean isOdd = false;
if(total%2 != 0){
isOdd = true;
}
while(true){
//grow
//System.out.println("xx");
if( p1<nums1.length && p2<nums2.length && nums1[p1] < nums2[p2] ){
temp[p]=nums1[p1];
p1++;
p++;
}
if( p1<nums1.length && p2<nums2.length && nums1[p1] >= nums2[p2]) {
temp[p]=nums2[p2];
p2++;
p++;
}
//rest
if(p1 == nums1.length && p2 < nums2.length ||nums1.length==0 && p2 < nums2.length){
//go p2
temp[p]=nums2[p2];
p2++;
p++;
//System.out.println(temp[p-1]);
}
if(p2 == nums2.length && p1 < nums1.length ||nums2.length==0 && p1 < nums1.length){
//go p2
temp[p]=nums1[p1];
p1++;
p++;
}
if(p > total/2){
break;
}
}
if(isOdd){
return temp[total/2];
}
else{
return
(temp[total/2-1]+temp[total/2])/2.0;
}
}
public static void main(String args[]){
Solution s = new Solution();
int nums1 []={3,4,7};
int nums2 []= {2};
System.out.println(s.findMedianSortedArrays(nums1, nums2));
}
}
基本思路是:因为是两个已经排好序的数组,那么可以将两个数组合并成一个数组,再去计算中位数。实现的话用到的应该是数据结构里面的基础知识。
提交的时候对于特殊值 [] [1], [1][1] 的情况报错,花了一些时间修改边界条件。往往细节的地方很重要,觉得思考需要更严谨一些。