[LeetCode_PY] Median of Two Sorted Arrays
来源:互联网 发布:无法添加数据连接 编辑:程序博客网 时间:2024/06/06 00:49
题目:
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)).
思路:
方法一:
先做最笨的方法,两个列表合并,排序,找到中间的那个。
python2.7 稍微处理一下整除的问题。
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums3 = nums1 + nums2 nums3.sort() size = len(nums3) if size % 2 : return nums3[ size /2 ] else: return ( nums3[ size /2 - 1 ] + nums3[ size /2 ] ) / 2.0
居然accept,复杂度显然是不满足,这里面复杂度是(m+n)log(m+n)
方法二:
k = (m + n )/ 2 已知两个有序列表,求第K大的数。
找一找第K大的数,应该用什么方法,堆排序什么的,或者二分查找看看能不能用上。最后找到了一个,折半排除的方法
#!/usr/bin/env python# -*- coding: UTF-8 -*-def findKth(a, a_start, a_len, b, b_start, b_len, k): """ :type a: List[int] :a_start: a 开始的下标 """ if a_len > b_len: return findKth(b, b_start, b_len, a, a_start, a_len, k) if a_len == 0: return b[b_start + k - 1 ] if k == 1: return min(a[a_start], b[b_start]) pa = min( k / 2, a_len ) pb = k - pa if a[a_start + pa - 1] < b[b_start + pb - 1]: return findKth(a, a_start + pa , a_len - pa, b, b_start, b_len, k - pa) elif a[a_start + pa - 1] > b[b_start + pb - 1]: return findKth(a, a_start, a_len, b, b_start + pb, b_len - pb, k - pb) else: return a[a_start + pa - 1]class Solution(): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ sum_len = len(nums1) + len(nums2) if sum_len % 2 : return findKth(nums1, 0, len(nums1), nums2, 0, len(nums2), sum_len / 2 + 1) else: return (findKth(nums1, 0, len(nums1), nums2, 0, len(nums2), sum_len / 2 ) + findKth(nums1, 0, len(nums1), nums2, 0, len(nums2), sum_len / 2 + 1)) / 2.0
0 0
- [LeetCode_PY] 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
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- MySql5.7 ERROR 1820 (HY000): You must SET PASSWORD before executing this statement
- MySql 小数型
- TextView显示不同颜色字体的实现
- vs2013配置opencv2.4.9
- oracle 面试题
- [LeetCode_PY] Median of Two Sorted Arrays
- Android代码中自己写的一些工具类(整理)
- MFC删除MSComm控件出现error LNK1120和LNK2001错误
- 曾经,美艺达见证了我们的爱情,如今,你在哪里?
- ufw配置手册
- 【PA2010】【BZOJ3493】Termites
- 持续交付的Mesos与Docker导入篇
- void指针的用法
- VS2013+OpenCV249+Windows10环境配置