leetcode4尋找兩個正序數組的中位數

在這裏插入圖片描述
方法一:將兩個數組合並尋找中位數,時間複雜度O(m+n)
方法二:二分法

主要思路:要找到第 k (k>1) 小的元素,那麼就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1] 進行比較,這裏的 “/” 表示整除
* nums1 中小於等於 pivot1 的元素有 nums1[0 … k/2-2] 共計 k/2-1 個
* nums2 中小於等於 pivot2 的元素有 nums2[0 … k/2-2] 共計 k/2-1 個
* 取 pivot = min(pivot1, pivot2),兩個數組中小於等於 pivot 的元素共計不會超過 (k/2-1) + (k/2-1) <= k-2 個
* 這樣 pivot 本身最大也只能是第 k-1 小的元素
* 如果 pivot = pivot1,那麼 nums1[0 … k/2-1] 都不可能是第 k 小的元素。把這些元素全部 “刪除”,剩下的作爲新的 nums1 數組
* 如果 pivot = pivot2,那麼 nums2[0 … k/2-1] 都不可能是第 k 小的元素。把這些元素全部 “刪除”,剩下的作爲新的 nums2 數組
* 由於我們 “刪除” 了一些元素(這些元素都比第 k 小的元素要小),因此需要修改 k 的值,減去刪除的數的個數
*/
圖文見:詳細圖文介紹

class Solution {
public:
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
		int len1 = nums1.size();
		int len2 = nums2.size();
		int k = 0;
		if ((len1 + len2) % 2 == 0)
			return (getKthElement(nums1, nums2, (len1 + len2) / 2) + getKthElement(nums1, nums2, (len1 + len2) / 2 + 1)) / 2.0;
		else
			return getKthElement(nums1, nums2, (len1 + len2) / 2+1);
	}
	int getKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {
		int len1 = nums1.size();
		int len2 = nums2.size();
		int index1 = 0, index2 = 0;
		while (true) {
			if (index1 == len1)
				return nums2[index2 + k - 1];
			if (index2 == len2)
				return nums1[index1 + k - 1];
			if (k == 1)
				return min(nums1[index1], nums2[index2]);//如果k==1,返回較小值
			int newindex1 = min(index1 + k / 2 - 1, len1 - 1);//防止出現越界
			int newindex2 = min(index2 + k / 2 - 1, len2 - 1);
			if (nums1[newindex1] < nums2[newindex2]) {//更新nums1的起始地址和k
				k -= newindex1 - index1 + 1;
				index1 = newindex1+1;
			}
			else {
				k -= newindex2 - index2 + 1;
				index2 = newindex2+1;
			}

				
		}
	}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章