LeetCode-Median of Two Sorted Arrays-解题报告

原题链接 https://leetcode.com/problems/median-of-two-sorted-arrays/

There are two sorted arrays nums1 and nums2 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(vector<int>& nums1, vector<int>& nums2) {
		int i = 0, j = 0, s = 0, m = nums1.size(), n = nums2.size();
		bool flag = false;
		int ans = 0;
		int mid;
		if ((m + n) & 1)flag = true, mid = (m + n) / 2 + 1;
		else mid = (m + n) / 2;
		while (s != mid)
		{
			if (i < m && j < n)
			{
				if (nums1[i] > nums2[j])ans = nums2[j], j++;
				else if (j < n)ans = nums1[i], i++;
			}
			else if (i >= m && j < n)
				ans = nums2[j++];
			else if (i < m && j >= n)
				ans = nums1[i++];
			s++;
		}
		if (flag)return ans;
		else
		{
			if (j >= n && i < m)
				return (double)(ans + nums1[i]) / 2;
			if (i >= m && j < n)
				return (double)(ans + nums2[j]) / 2;
			return (double)(ans + min(nums1[i], nums2[j])) / 2;
		}
	}
};


阅读更多
文章标签: C++ leetcode
上一篇LeetCode-Reverse Integer-解题报告
下一篇LeetCode-Add Two Numbers-解题报告
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭