leetcode 4. Median of Two Sorted Arrays

Datetime:2016-08-23 01:20:35          Topic: LeetCode           Share

https://leetcode.com/problems/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 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
 4         vector<int> nums3;
 5         int i=0,j=0,k=0;
 6         int m =(nums1.size()+nums2.size());
 7         while(i<nums1.size()&&j<nums2.size()) {
 8             if(nums1[i]<nums2[j])
 9                   nums3.push_back(nums1[i++]);
10             else
11                 nums3.push_back(nums2[j++]);
12             k++; 
13             if(k>m/2)
14               {
15                   if(m%2)
16                   return nums3[k-1];
17                   else
18                   return (nums3[k-1]+nums3[k-2])/2.0;
19               }
20             }
21         while(i<nums1.size()){
22             nums3.push_back(nums1[i++]);
23             k++;
24              if(k>m/2)
25               {
26                   if(m%2)
27                   return nums3[k-1];
28                   else
29                   return (nums3[k-1]+nums3[k-2])/2.0;
30               }
31             }
32              while(j<nums2.size()){
33             nums3.push_back(nums2[j++]);
34             k++;
35              if(k>m/2)
36               {
37                   if(m%2)
38                   return nums3[k-1];
39                   else
40                   return (nums3[k-1]+nums3[k-2])/2.0;
41               }
42             }
43             return 0 ;
44     }
45 };

在leetcode中时间为48ms。





About List