算法课第十五周作业 | Median of Two Sorted Arrays
来源:互联网 发布:淘宝卖家需要的软件 编辑:程序博客网 时间:2024/06/08 05:47
写在前面:
选取leetcode的第4题,使用排序的方法解题。
题意解读:
给定两个整数数组,两个数组的大小不一样,求这两个数组集合的中位数。
如果数组集合是偶数,则中位数是中间两个数的平均值,如果是奇数个,则中位数就是最中间的一个。
要求计算复杂度不要找过O(log(m+n)),其中m,n分布是两个数组的个数。
解题思路:
现将两个数组合并为一个,放进all里,用vector容器的sort函数进行排序,
sort函数采用的快速排序算法,是目前最快的排序算法。
接着判断(m+n)的奇偶性,返回相应的结果。
代码:
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> all(nums1.begin(), nums1.end()); all.insert(all.begin(),nums2.begin(), nums2.end()); sort(all.begin(), all.end()); double result; if((nums1.size() + nums2.size()) % 2 == 1) { int r = (nums1.size() + nums2.size()) /2; result = all[r]; } else { result = (double)(all[(nums1.size() + nums2.size()) /2] + all[(nums1.size() + nums2.size()) /2-1]) / 2; } return result; }};
阅读全文
0 0
- 算法课第十五周作业 | Median of Two Sorted Arrays
- 算法分析课每周练习 Median of Two Sorted Arrays
- 算法第三周Median of Two Sorted Arrays[hard]
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- CSS绘制三角形
- redis实现web页面缓存
- 算法分析与设计课程12——486. Predict the Winner
- 用tarjan缩点重建图
- sql语句的简单用法
- 算法课第十五周作业 | Median of Two Sorted Arrays
- 系统学习前端之CSS 基础
- rhel7中,targetcli使用两位数的分区后缀名字(比如sda10)而导致的问题
- java单链表的翻转
- 解决mybatis generator生成实体类和数据库字段名不一致
- [UIViewController _loadViewFromNibNamed:bundle:] loaded the nib but the view outlet was not set
- android studio 中 Error:(12, 23) 错误: 程序包org.apache.http不存在
- GO语言method
- solr学习笔记 -- day05 solrJ的使用