天天看点

LintCode 931: Median of K Sorted Arrays (经典题)

这题我参考的九章的答案,感觉不容易。

解法1:

先求出所有数组的元素数目之和totalCount,然后直接用二分法查找从0到INT_MAX的所有数,检查函数是findKthLargestNumber(),它会检查某个vector以及所有vector中有多少个数大于等于该数。

二分法的具体实现中,如果已经有多于k个数大于该数,那么说明这第k个数在(mid…end],若小于k个数大于该数,说明这第k个数在[start, mid)。关键点在于如果刚好k个数大于该数的处理,

注意:

  1. 为防溢出,even number的情况用

    findKthLargestNumber(nums, totalCount / 2) / 2.0 +

    findKthLargestNumber(nums, totalCount / 2 + 1) / 2.0;

class Solution {
public:
    /**
     * @param nums: the given k sorted arrays
     * @return: the median of the given k sorted arrays
     */
    double findMedian(vector<vector<int>> &nums) {
        if (nums.size() == 0) return 0;
        
        int totalCount = 0;
        
        for (int i = 0; i < nums.size(); ++i) {
            totalCount += nums[i].size();    
        }
        
        if (totalCount & 0x1) {
        //odd number
            return findKthLargestNumber(nums, totalCount / 2 + 1);
        } else {
        //even number
            return findKthLargestNumber(nums, totalCount / 2) / 2.0 + 
                   findKthLargestNumber(nums, totalCount / 2 + 1) / 2.0;

        }
    }
    
    int findKthLargestNumber(vector<vector<int>> &nums, int k) {
        int start  = 0;
        int end = INT_MAX;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (getGTECount(nums, mid) >= k) {
                start = mid;
            } else {
                end = mid;
            }
        }    
        
        if (getGTECount(nums, start) >= k) return start;
        
        return end;
    }
    
    int getGTECount(vector<vector<int>> &nums, int val) {
        int count = 0;
        
        for (int i = 0; i < nums.size(); ++i) {
            count += getGTECount(nums[i], val);
        }
        
        return count;
    }
    
    int getGTECount(vector<int> &nums, int val) {
        if (nums.size() == 0) return 0;
        int start = 0;
        int end = nums.size() - 1;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= val) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (nums[start] >= val) return nums.size() - start;
        if (nums[end] >= val) return nums.size() - end;
        return 0;
    }
};