LeetCode - Median of Two Sorted Arrays

Median of Two Sorted Arrays

2013.12.1 19:29

There are two sorted arrays A and B 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)).

 

Solution:

  Given two sorted array, find out the median of all elements. My solution is straightforward, merge two arrays and return the median.

  Time complexity is O(m + n), space complexity O(m + n) as well. In-place merge is too much trouble, and merging by swapping have some bad case of O(n^2) time compleity. So the direct solution is sometimes a wise solution at all :) 

  Here is the accepted code.

Accepted code:

 1 // 1RE 1AC

 2 class Solution {

 3 public:

 4     double findMedianSortedArrays(int A[], int m, int B[], int n) {

 5         // IMPORTANT: Please reset any member data you declared, as

 6         // the same Solution instance will be reused for each test case.

 7         merge(A, m, B, n);

 8         if((m + n) % 2 == 1){

 9             return C[(m + n - 1) / 2];

10         }else{

11             return (C[(m + n) / 2 - 1] + C[(m + n) / 2]) / 2.0;

12         }

13     }

14 private:

15     vector<int> C;

16     

17     void merge(int A[], int m, int B[], int n) {

18         C.clear();

19         

20         int i, j;

21         

22         i = j = 0; // Bugged here, omitted this sentence

23         while(i < m && j < n){

24             if(A[i] <= B[j]){

25                 C.push_back(A[i++]);

26             }else{

27                 C.push_back(B[j++]);

28             }

29         }

30         

31         while(i < m){

32             C.push_back(A[i++]);

33         }

34         

35         while(j < n){

36             C.push_back(B[j++]);

37         }

38     }

39 };

 

你可能感兴趣的:(LeetCode)