查询两个数组的中位数
来源:互联网 发布:swmm软件下载 编辑:程序博客网 时间:2024/06/18 06:00
查询两个数组的中位数
Median of Two Sorted Arrays
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,则中位数的位置一定能确定,len(nums1) + len(nums2) / 2的取整值,记为median_idx
- 需要区分是len(nums1) + len(nums2)是奇数还是偶数
- 两个指针,只需要从nums1和nums2头部开始往后移动,将两者中较小值放入新的数组
- 当新的数组的长度达到了median_idx,即可求中位数
- 过程中需要注意两个数组长度不等的情况,防止下标越界
代码
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ median_idx = int((len(nums1) + len(nums2)) / 2) index1, index2 = 0, len(nums1) combine_list = nums1 + nums2 new_list = [] i = 0 while i <= median_idx: if index1 < len(nums1) and index2 - len(nums1) < len(nums2): new_list.append(min(combine_list[index1], combine_list[index2])) if combine_list[index1] < combine_list[index2]: index1 += 1 else: index2 += 1 elif index1 >= len(nums1): # nums1 is out of range, append nums2 new_list.append(combine_list[index2]) index2 += 1 elif index2 >= len(nums2): # nums2 is out of range, append nums1 new_list.append(combine_list[index1]) index1 += 1 i += 1 if (len(nums1) + len(nums2)) % 2 == 0: median = float(new_list[median_idx] + new_list[median_idx - 1]) / 2 else: median = new_list[median_idx] return median
本题以及其它leetcode题目代码github地址: github地址
阅读全文
0 0
- 查询两个数组的中位数
- 两个数组的中位数
- 两个有序数组的中位数
- 两个排序数组的中位数
- 两个排序数组的中位数
- 两个有序数组的中位数
- 两个升序数组的中位数
- 两个排序数组的中位数
- 两个排序数组的中位数
- 两个有序数组的中位数
- 两个排序数组的中位数
- 两个有序数组的中位数
- 两个排序数组的中位数
- 寻找两个数组的中位数
- 两个排序数组的中位数
- 两个有序数组的中位数
- 两个排序数组的中位数
- 两个有序数组的中位数
- L1-002. 打印沙漏
- jQuery阶段总结
- dubbo服务集群配置及负载均衡策略
- 面向对象编程进阶
- NoSQL数据库数据模型(笔记)
- 查询两个数组的中位数
- 求一棵二叉树的镜像
- 虚函数专题
- jQuery
- c++11 多线程基础
- React学习——JSX的使用
- EditPlus、Notepad++等编辑器选中列(块)的方法
- Ajax和JQuery的$.ajax
- (个人)AR电子书系统创新实训第四周(2)