Leetcode:4. Median of Two Sorted Arrays
来源:互联网 发布:the weeknd earned it 编辑:程序博客网 时间:2024/06/05 07:44
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, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
解题思路
最简单的办法肯定是对两个数组进行合并,找到第k个即可,但是这样时间复杂度比较高O(m+n),空间复杂度为O(m+n)。一个新的办法是,设计一个新的接口findKth,返回两个数组第k个元素。题目分两种情况:一种是当两个数组size之和为偶数时,那么就是中间两个数求平均,另外一种是两个数组之和为奇数时,就是最中间那个数。
时间复杂度、空间复杂度分析
代码
class Solution {public: double findKth(vector<int> &a, int aStart, int aLength, vector<int> &b, int bStart, int bLength, int k) { // k start from 1 if(aLength > bLength) // 默认 b比较长 return findKth(b, bStart, bLength, a, aStart, aLength, k); if(aLength == 0) //a为空 return b[bStart + k -1]; if(k == 1) return min(a[aStart] , b[bStart]); int pa = min(k/2, aLength); int pb = k - pa; if(a[aStart + pa - 1] < b[bStart + pb -1]) //a[aStart + pa - 1] k 肯定不在这里面,所以直接截掉 减小问题规模 return findKth(a, aStart + pa, aLength - pa, b, bStart, bLength, k - pa); else if(a[aStart + pa - 1] > b[bStart + pb -1])// b[bStart + pb -1] k 肯定不在这里面,所以直接截掉 减小问题规模 return findKth(a, aStart, aLength, b, bStart + pb, bLength - pb, k -pb); else return a[aStart + pa - 1]; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int size = nums1.size() + nums2.size(); if(size & 0x1)//试试新的 看最后一位是否为1 size % 2 == 1 return findKth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), size/2 + 1); else return (findKth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), size/2 + 1) + findKth(nums1, 0, nums1.size(), nums2, 0, nums2.size(), size/2)) / 2.0; }};
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
- [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
- 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
- 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
- 在单链表上实现插入排序
- 第三周 项目四——顺序表应用(2)
- <Pro ASP.NET MVC 5> - Note02
- poj3686 The Windy's(拆点,费用流,好题)
- 详细解读LruCache类
- Leetcode:4. Median of Two Sorted Arrays
- C#控制台基础 创建文件夹
- 常用正则表达式实例
- 第三周 项目1-顺序表的基本运算
- 青岛网赛 1006 HDU 5883 The Best Path
- 自定义UIPresentationController
- Linux文件压缩与解压总结
- 003 个位数统计
- C语言调用Window/Linux上的各种应用程序