4. Median of Two Sorted Arrays
来源:互联网 发布:java培训机构课程安排 编辑:程序博客网 时间:2024/06/09 00:40
题目: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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 4]
nums2 = [3, 4]
The median is (2+3)/2=2.5
思路: 这道题目是限制了时间复杂度的,想了很久没做出来,便直接在网上看参考了,https://discuss.leetcode.com/topic/16797/very-concise-o-log-min-m-n-iterative-solution-with-detailed-explanation/2,代码如下:
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); if (m < n) return findMedianSortedArrays(nums2, nums1); if (n == 0) return ((double)nums1[(m - 1) / 2] + (double)nums1[m / 2]) / 2.0; int left = 0, right = n * 2; while (left <= right) { int mid2 = (left + right) / 2; int mid1 = m + n - mid2; double L1 = mid1 == 0 ? INT_MIN : nums1[(mid1 - 1) / 2]; double L2 = mid2 == 0 ? INT_MIN : nums2[(mid2 - 1) / 2]; double R1 = mid1 == m * 2 ? INT_MAX : nums1[mid1 / 2]; double R2 = mid2 == n * 2 ? INT_MAX : nums2[mid2 / 2]; if (L1 > R2) left = mid2 + 1; else if (L2 > R1) right = mid2 - 1; else return (max(L1, L2) + min(R1, R2)) / 2; } return -1; }};
阅读全文
0 0
- [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
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- leetcoode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- Calico 的网络结构是什么?- 每天5分钟玩转 Docker 容器技术(68)
- Connection类
- cvte2018秋季招聘c++开发面试面经
- 数据库连接池的类别
- 反序列化(层序)
- 4. Median of Two Sorted Arrays
- Lua语法结构之表达式
- intersection set
- 好久不见>_< 转载 java有关泛型方法重载
- c++循环语句中变量的生存周期
- usaco Milking Cows
- C语言初步-第32讲:循环思想启蒙(输出小星星)
- 指针 和引用 || 静态成员函数 || 虚函数 || 系统调用和库函数 ||
- MySQL:datediff函数