LeetCode第四题:Median of Two Sorted Arrays(c++)详解

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

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

class Solution {
public:
    double findMedianSortedArrays(vector& nums1, vector& nums2) {
        vector combineArray;
        for(int i = 0, j = 0;i< nums1.size() || j < nums2.size();)
        {
            if(i> 1;//求取中位数
        if(middle % 2 == 1)
        {
            return (double)combineArray[middle];
        }
        else
        {
            return ((double)combineArray[middle] + (double)combineArray[middle-1])/2.0;
        }
        //二分查找
    }
};

解题思路:

  1. 将二个有序数组组装成一个有序数组,因二个数组都是有序,可采用比较数值大小,即可按大小组装成一个有序数组,千万不可遍历二个数组组装成一个数组,再排序,这样复杂度将不满足要求;
  2. 随后采用二分法即可获取最后结果。

总结:
1.习惯了IDE的自动补全,生写很是不适用;
2.不可调试,真是特别难受;
3.手撕代码真正考验对数据结构得理解;
4.继续加油,work,work。

你可能感兴趣的:(leetcode)