LeetCode:Median of Two Sorted Arrays
2017-08-05 16:13
483 查看
题目:
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
给定两个已经排序好的数组,找到所有元素的中位数。要求时间复杂度为O(log (m+n)).
思路:
找到所有元素的中位数的问题可以转化为找第K大数的问题,我们可以用两个计数器p,q分别指向A,B数组的第一个元素,如果A数组的当前元素小,则p++,如果B数组的当前元素小,则q++,最终可以找到第K大的数。代码:
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int L1=nums1.size(); int L2=nums2.size(); int total=L1+L2; if(total%2) return findkth(nums1,nums2,total/2+1); else return (findkth(nums1,nums2,total/2)+findkth(nums1,nums2,total/2+1))/2.0; } double findkth(vector<int>& nums1, vector<int>& nums2,int k){ int p=0;int q=0; for(int i=0;i<k-1;i++){ if(p>=nums1.size()&&q<nums2.size()) q++; else if(q>=nums2.size()&&p<nums1.size()) p++; else if(nums1[p]<nums2[q]) p++; else q++; } if(p>=nums1.size()) return nums2[q]; else if(q>=nums2.size()) return nums1[p]; else return min(nums1[p],nums2[q]); } };
相关文章推荐
- LeetCode第四题(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
- LeetCode(4)Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- 【LeetCode】Median of Two Sorted Arrays
- leetcode: Median of Two Sorted Arrays
- 【Leetcode】Median of Two Sorted Arrays
- LeetCode4/88 Median of Two Sorted Arrays/Merge Sorted Array
- Leetcode 4 Median of Two Sorted Arrays
- leetcode-4-Median of Two Sorted Arrays
- [LeetCode_PY] Median of Two Sorted Arrays
- [leetcode]Median of Two Sorted Arrays
- LeetCode(4)Median of Two Sorted Arrays
- LeetCode week 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:Median of Two Sorted Arrays