meadian of two sorted arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
题目:
Median of Two Sorted Arrays
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 (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

思路

  • 将两个排序数组整个到一个数组,并进行排序
  • 在排序后的数组中找出中位数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution{
public double findMedianSortedArrays(int[] nums1,int[] nums2){
int len1 = nums1.length;
int len2 = nums2.length;
int[] result = new result[len1+len2];
System.arraycopy(nums1,0,result,0,len1);
System.arraycopy(nums2,0,result,len1,len2);
Arrays.sort(result); //很好用的排序函数,对数组对象都可以排序
int temp = (len1 + len2) % 2;
int count = (len1 + len2) / 2;
double median = 0;
if(temp == 0){
median = (double)(result[count - 1] + result[count])/2; //需要将右边转型为double,否则结果都只保留整数,需要注意函数最后返回什么类型的值
}else{
median = (double)result[count];
}
return median;
}
}