1. 程式人生 > >LeetCode-4 兩個排序陣列的中位數

LeetCode-4 兩個排序陣列的中位數

class Solution {
private:
	int min(int v1, int v2) {
		if (v1 > v2) {
			return v2;
		}
		return v1;
	}

	double getKth(vector<int>& nums1, vector<int>& nums2, int begin1, int begin2, int k) {
		if (nums1.size() - begin1 > nums2.size() - begin2) {
			return getKth(nums2, nums1, begin2, begin1, k);
		}
		else if (nums1.size() == begin1) {
			return nums2[k + begin2 - 1];
		}
		else if (k == 1) {
			return min(nums1[begin1], nums2[begin2]);
		}

		int i = min(nums1.size() - begin1, k / 2);
		int j = min(nums2.size() - begin2, k / 2);

		if (nums1[i + begin1 - 1] < nums2[j + begin2 - 1]) {
			return getKth(nums1, nums2, begin1 + i, begin2, k - i);
		}
		else {
			return getKth(nums1, nums2, begin1, begin2 + j, k - j);
		}
	}

public:
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
		int len1 = nums1.size();
		int len2 = nums2.size();
		return (getKth(nums1, nums2, 0, 0, (len1 + len2 + 1) / 2) + getKth(nums1, nums2, 0, 0, (len1 + len2 + 2) / 2)) / 2.0;
	}
};