Median of Two Sorted Arrays

来源:互联网 发布:深圳海关进出口数据 编辑:程序博客网 时间:2024/06/14 10:33

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

这也算是一道经典题目了吧。背景应该是并归排序。

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        double val = -1;        int len = m + n;int half = len / 2;if(len % 2 == 1)//当长度为奇数时的处理{half++;}        int i = 0, j = 0;while(half > 0){if(j >= n || i < m && A[i] <= B[j]){val = A[i++];}else{val = B[j++];}half--;}if(len % 2 == 0)//当长度为偶数时的处理{if(j >= n || i < m && A[i] <= B[j]){val = (val + A[i]) / 2;}else{val = (val + B[j]) / 2;}}return val;    }};

0 0
原创粉丝点击