4. 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 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;
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值