[leetcode] 4. Median of Two Sorted Arrays 解题报告
来源:互联网 发布:unity3d怎么打包资源 编辑:程序博客网 时间:2024/06/08 14:57
题目链接: 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)).
思路: 这也算是一道很经典的问题了, 其原理还是和一个数组求中位数的二分搜索相似.
又是很抱歉的一题, 原来的算法时间复杂度是O(m+n), 因为包含了数组的复制, 而我隐约觉得不太对, 但没有仔细分析时间复杂度, 昨天再一看居然是错的, 实在不好意思.
A[i-1] A[i]
B[j-1] B[j]
要找到这样一个十字交叉的位置, 也就是i+j = n/2, 使得A[i-1] <= B[j], B[j-1] <= A[i], 这样对于只有一个中位数的取max(A[i-1], B[j-1]), 对于两个中位数的则取(max(A[i-1], B[j-1]), min(A[i], B[j]))/2;
代码如下:
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { if(nums1.size() > nums2.size()) nums1.swap(nums2); int len1=nums1.size(), len2=nums2.size(); int mid=(len1+len2-1)/2, left=0, right=len1-1; while(left <= right) { int mid1 = (left+right)/2, mid2 = mid - mid1; if(nums1[mid1] >= nums2[mid2]) right = mid1-1; else left = mid1+1; } double med1=max(left>0?nums1[right]:INT_MIN, nums2[mid-left]); if((len1+len2)%2) return med1; double med2=min(left<len1?nums1[left]:INT_MAX, mid-right<len2?nums2[mid-right]:INT_MAX); return (med1 + med2)/2; }};
0 0
- [leetcode] 4. Median of Two Sorted Arrays 解题报告
- Leetcode解题报告:4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays 解题报告
- LeetCode-Median of Two Sorted Arrays-解题报告
- Leetcode (4) Median of Two Sorted Arrays 解题报告
- [LeetCode] Median of Two Sorted Arrays 解题报告
- [LeetCode] Median of Two Sorted Arrays 解题报告
- LeetCode 4 Median of Two Sorted Arrays 解题报告
- [LeetCode 解题报告]004.Median of Two Sorted Arrays
- LeetCode(4) Median of Two Sorted Arrays解题报告
- Leetcode Median of two sorted arrays解题
- 【LeetCode】4.Median of Two Sorted Arrays 解题
- Leetcode解题笔记 4.Median of Two Sorted Arrays [Hard]
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 机器学习中的隐马尔科夫模型(HMM)详解
- Mac下ProxyChains Tor实现shell代理,隐藏自己的ssh登陆ip
- 手机安全卫士第三天
- LeetCode 335. Self Crossing(贪吃蛇)
- html5 web IndexedDB使用详解
- [leetcode] 4. Median of Two Sorted Arrays 解题报告
- C语言 字符串匹配问题,KMP函数-失配函数
- 有限元笔记1-高斯积分
- PHP与Zend公司简介
- IDEA如何打包可运行jar的一个问题。
- HDU 2019 数列有序!(水题)
- HDU 2020 绝对值排序(排序)
- 路由配置:理解secondary ip address
- 分区表