leetcode.C.4. Median of Two Sorted Arrays

Posted Protogenoi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode.C.4. Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。

4. Median of Two Sorted Arrays

这应该是最简单最慢的方法了,因为本身为有序,所以比较后排序再得到中位数。

 1 double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
 2     int numsSize = nums1Size + nums2Size;
 3     int *nums = (int*)malloc(sizeof(int)*numsSize);
 4     double median;
 5     //合并
 6     for (int i = 0, j = 0, k = 0; k < numsSize; k++) {
 7         if (i >= nums1Size)    nums[k] = nums2[j++];
 8         else if (j >= nums2Size)    nums[k] = nums1[i++];
 9         else {
10             if (nums1[i] >= nums2[j])nums[k] = nums2[j++];
11             else nums[k] = nums1[i++];
12         }
13     }
14     //中卫
15     if (numsSize % 2 == 0)
16         median = (double) (nums[(int)(numsSize / 2 - 1)] + nums[(int)(numsSize / 2)]) / 2;
17     else median = (double)nums[numsSize / 2];
18     free(nums);
19     return median;
20 }

 

 

 

以上是关于leetcode.C.4. Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode--median-of-two-sorted-arrays

leedcode Median of Two Sorted Arrays

#Leetcode# 4. Median of Two Sorted Arrays

LeetCode: Median of Two Sorted Arrays

Leetcode 4. Median of Two Sorted Arrays(二分)

Median of two Sorted Arrays