LeetCode 4. Median of Two Sorted Arrays
来源:互联网 发布:ubuntu怎么移动文件夹 编辑:程序博客网 时间:2024/05/16 11:13
题目:
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
思路:
就是求两个数组合并后的数组的中位数,利用归并思想合并,再求中位数,不难。
计算nums1和nums2的长度len1、len2,记len为len1和len2的和,如果和都0,返回double类型的0。利用归并思想,如果i小于len1,j小于len2,将nums1[i]和nums2[j]中小的那个值放入res,并对应索引加1。上面循环结束,如果是i
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len1=nums1.size();//计算nums1和nums2的长度 int len2=nums2.size(); int len=len1+len2;//记len为len1和len2的和 if(len==0){//如果和都0,返回double类型的0 return double(0); } vector<int> res; int i=0,j=0;//利用归并思想 while(i<len1&&j<len2){//如果i小于len1,j小于len2 res.push_back(nums1[i]<nums2[j]?nums1[i++]:nums2[j++]);//将nums1[i]和nums2[j]中小的那个值放入res,并对应索引加1 } while(i<len1){//上面循环结束,如果是i<len1,也就是j已经到达len2,将nums1中剩余的数放入res res.push_back(nums1[i++]); } while(j<len2){//上面循环结束,如果是j<len2,也就是i已经到达len1,将nums2中剩余的数放入res res.push_back(nums2[j++]); } if((len1+len2)%2==0){//如果总个数为偶数个,则中位数为索引值为len/2与len/2-1的两个值转换为double类型后的平均值 return ((double(res[len/2])+double(res[len/2-1]))/2); } else{//如果总个数为奇数,中位数为索引值为len/2的那个值转换为double类型后的值 return double(res[len/2]); } }};
输出结果: 52ms
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
- Java构造方法的相互调用
- [LeetCode]97. Interleaving String
- spring security 自定义filter参考资料
- 博客什么的写也就写了
- tpshop授权如何判断
- LeetCode 4. Median of Two Sorted Arrays
- PHP函数详解:call_user_func()使用方法
- Delphi XE6,C++ Builder XE6,RAD Studio XE6 v20.0.16277.1276(With Update 1) 官方下载激活
- Shell Cheatsheet
- 面向对象:ATM Use Case 及用况图文档
- LeetCode 75. Sort Colors
- Andriod Service基本用法篇
- echarts的引入和使用
- [CF 417D]Cunning Gena:状压DP