LeetCode_004 Median of Two Sorted Arrays 【Updating...】

版权声明:转载请注明出处 https://blog.csdn.net/qq_42292831/article/details/85600442

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)).

You may assume nums1 and nums2 cannot be both empty.

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

* 网站上的测试增加了许多错误检测机制,例如在循环过程中就不允许下标直接越界,尽管越界下标没有被使用;

(见下方注释掉的冒泡排序) 

************************************************************************************************************************************

思路一【O(mn)】:

组合+冒泡+取中位数返回

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {

    int *a = (int *)malloc(sizeof(int)*(nums1Size+nums2Size));
    //int *a = (int *)malloc(sizeof(int)*(nums1Size+nums2Size)+1); //防止第二种冒泡排序的越界检测
    int total_length=nums1Size+nums2Size;
    int temp_number =0;
    for(int i=0;i<nums1Size;i++)
    {
        a[i] = nums1[i];
    }
    for(int j =0,k=nums1Size;j<nums2Size;j++,k++)
    {
        a[k] = nums2[j];
    }
    
    
    for(int i =total_length-1;i>0;i--)
    //for(int i =0;i<=total_length-i;i++)
    {
        bool flag = false;
        for(int j = 0;j<i;j++)
        //for(int j = 0;j<total_length-i;j++)
        {
            if(a[j]<=a[j+1])
            {
                temp_number = a[j];
                a[j] = a[j+1];
                a[j+1] = temp_number;
                flag = true;
            }
        }
        if(!flag)
        {
            break;
        }
    }

      
    if(total_length%2==1)
    {
        int middle = (total_length)/2;
        double result = a[middle];
        return result;
    }
    else
    {
        double result = ((double)a[(total_length)/2]+a[(total_length)/2-1])/2;
        return result;
    }
    return 0;
}

思路二【O(m+n)】:

数组归并(直接有序存储)+ 取出中位数返回

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    int num[nums1Size + nums2Size];
    int i = 0, j = 0, k = 0;
    double a;
    while(i < nums1Size && j < nums2Size){
        if(nums1[i] < nums2[j])
            num[k++] = nums1[i++];
        else
            num[k++] = nums2[j++];
    }
    while(i < nums1Size){
        num[k++] = nums1[i++];
    }
    while(j < nums2Size){
        num[k++] = nums2[j++];
    }
    
    if(k%2 == 1)
        return num[k/2];
    else{
        i = k/2;
        a = (double)(num[i-1] + num[i]) / 2;
        return a;
    }
}

思路三【O(log2(m+n))】(Updating...)

猜你喜欢

转载自blog.csdn.net/qq_42292831/article/details/85600442