题目:
具体的实现方法,在网上都可以查到。
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
分析总结:
1、根据题目可以知道,该算法是对空间复杂度有要求的,要是log(m+n);而我们常用的排序算法的复杂度为
排序方法 | 平均情况 | 最好情况 | 最坏情况 |
直接插入排序 | O(n2) | O(n) | O(n2) |
起泡排序 | O(n2) | O(n) | O(n2) |
快速排序 | O(nlog2n) | O(nlog2n) | O(n2) |
简单选择排序 | O(n2) | O(n2) | O(n2) |
堆排序 | O(nlog2n) | O(nlog2n) | O(nlog2n) |
归并排序 | O(nlog2n) | O(nlog2n) | O(nlog2n) |
所以根据复杂度情况可以知道只有直接插入排序和 冒泡排序法的最好情况符合要求,这里我选择了直接插入排序。
代码方式:
1、先对两部分代码分别进行排序,而后在对代码进行整合。
2、先整合后排序。
我的代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] a = nums1;
int[] b = nums2;
int[] last_nums=new int[a.length+b.length];
insert_sort insert_sort = new insert_sort();
insert_sort.insertion_sort(a);
insert_sort.insertion_sort(b);
int last_a=0, last_b=0;
System.out.println(a.length+b.length);
for(int i=0;i<(a.length+b.length);i++){
if(last_a <a.length && last_b < b.length){
if(a[last_a]<b[last_b]){
last_nums[i]=a[last_a];
last_a++;
}
else {
last_nums[i]=b[last_b];
last_b++;
}
}
else if(last_a == a.length){
last_nums[i]=b[last_b];
last_b++;
}
else if(last_b == b.length){
last_nums[i] = a[last_a];
last_a++;
}
//System.out.println(last_nums[i]);
}
if(last_nums.length%2==0){
return (last_nums[last_nums.length/2]+last_nums[last_nums.length/2-1])/2f;
}
else {
return last_nums[last_nums.length/2];
}
}
}
class insert_sort{
public void insertion_sort(int[] unsorted)
{
for (int i = 1; i < unsorted.length; i++)
{
if (unsorted[i - 1] > unsorted[i])
{
int temp = unsorted[i];
int j = i;
while (j > 0 && unsorted[j - 1] > temp)
{
unsorted[j] = unsorted[j - 1];
j--;
}
unsorted[j] = temp;
}
}
}
}