class Solution {
public:
int getKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {
/* 主要思路:要找到第 k (k>1) 小的元素疹鳄,那么就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1] 進(jìn)行比較
* 這里的 "/" 表示整除
* nums1 中小于等于 pivot1 的元素有 nums1[0 .. k/2-2] 共計(jì) k/2-1 個(gè)
* nums2 中小于等于 pivot2 的元素有 nums2[0 .. k/2-2] 共計(jì) k/2-1 個(gè)
* 取 pivot = min(pivot1, pivot2)讽挟,兩個(gè)數(shù)組中小于等于 pivot 的元素共計(jì)不會超過 (k/2-1) + (k/2-1) <= k-2 個(gè)
* 這樣 pivot 本身最大也只能是第 k-1 小的元素
* 如果 pivot = pivot1介杆,那么 nums1[0 .. k/2-1] 都不可能是第 k 小的元素媚值。把這些元素全部 "刪除",剩下的作為新的 nums1 數(shù)組
* 如果 pivot = pivot2劣领,那么 nums2[0 .. k/2-1] 都不可能是第 k 小的元素睦尽。把這些元素全部 "刪除",剩下的作為新的 nums2 數(shù)組
* 由于我們 "刪除" 了一些元素(這些元素都比第 k 小的元素要形噬鳌)萍摊,因此需要修改 k 的值,減去刪除的數(shù)的個(gè)數(shù)
*/
int m = nums1.size();
int n = nums2.size();
int index1 = 0, index2 = 0; //并不真的修改數(shù)組如叼,而是用index表示參與下一 步運(yùn)算的數(shù)組的左邊界
while (true) {
// 邊界情況
if (index1 == m) { //數(shù)組一已經(jīng)為空冰木,因?yàn)椴淮嬖趎um1[m]
return nums2[index2 + k - 1]; //這里的-1只是因?yàn)橛衝ums2[0]
}
if (index2 == n) {
return nums1[index1 + k - 1];
}
if (k == 1) { //找最小值時(shí)返回兩數(shù)組邊界的最小值
return min(nums1[index1], nums2[index2]);
}
// 正常情況
int newIndex1 = min(index1 + k / 2 - 1, m - 1); //若越界,則返回本數(shù)組最后 一個(gè)元素
int newIndex2 = min(index2 + k / 2 - 1, n - 1);
int pivot1 = nums1[newIndex1]; //pivot1=A[k/2-1]
int pivot2 = nums2[newIndex2];
if (pivot1 <= pivot2) {
k -= newIndex1 - index1 + 1; //k=k-k/2
index1 = newIndex1 + 1;//將newIndex1和它前面的元素移除數(shù)組
}
else {
k -= newIndex2 - index2 + 1;
index2 = newIndex2 + 1;
}
}
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int totalLength = nums1.size() + nums2.size();
if (totalLength % 2 == 1) { //m+n是奇數(shù)笼恰,返回第(m+n+1)/2個(gè)元素
return getKthElement(nums1, nums2, (totalLength + 1) / 2);
}
else {
return (getKthElement(nums1, nums2, totalLength / 2) + getKthElement(nums1, nums2, totalLength / 2 + 1)) / 2.0;
}
}
};
作者:LeetCode-Solution
鏈接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-s-114/
來源:力扣(LeetCode)
著作權(quán)歸作者所有踊沸。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)囚衔,非商業(yè)轉(zhuǎn)載請注明出處。
根據(jù)中位數(shù)的定義雕沿,