4. Median of Two Sorted Arrays-python
来源:互联网 发布:java手机 编辑:程序博客网 时间:2024/06/06 05:31
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.0Example 2:nums1 = [1, 2]nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Code
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ n1 = len(nums1) n2 = len(nums2) i = 0 j = 0 # sorting nums1 and nums2, sum pointer sumpointer = 0 while (i < n1 or j < n2) and sumpointer <= (n1 + n2) >> 1: if i >= n1: j+=1 elif j >= n2: i+=1 # combination nums1 and nums2 to sort elif nums1[i] <= nums2[j]: i+=1 else: j+=1 sumpointer+=1 even = (n1 + n2) % 2 == 0 i-=1 j-=1 if i < 0: return (nums2[j - 1] + nums2[j]) / 2.0 if even == True else nums2[j] if j < 0: return (nums1[i - 1] + nums1[i]) / 2.0 if even == True else nums1[i] # odd analysis if even==False: return max(nums1[i], nums2[j]) #even analysis, 1.shows stone point is in nums2 if nums1[i] < nums2[j]: if j - 1 >= 0 and nums1[i] <= nums2[j - 1]: return (nums2[j - 1] + nums2[j]) / 2.0 return (nums1[i] + nums2[j]) / 2.0 # shows stone point is in nums1 if i - 1 >= 0 and nums2[j] <= nums1[i - 1]: return (nums1[i - 1] + nums1[i]) / 2.0 return (nums1[i] + nums2[j]) / 2.0
阅读全文
2 0
- 4. Median of Two Sorted Arrays-python
- Median of Two Sorted Arrays -- leetcode -- Python
- leetcode04-Median of Two Sorted Arrays-python
- 【Leetcode】【python】Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays Leetcode Python
- [Leetcode]4. Median of Two Sorted Arrays @python
- LeetCode 4.Median of Two Sorted Arrays (Python)
- 【leetcode】4. Median of Two Sorted Arrays(Python & C++)
- [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
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- android随机整屏幕鲜花掉落
- sklearn 0.17 版本 方法过时问题
- bzoj 3688: 折线统计 (DP+树状数组)
- 162. Find Peak Element
- 创建线程并让它开始执行的实例
- 4. Median of Two Sorted Arrays-python
- 社工必备查询网址汇总
- 代码块详解
- 二叉树前序遍历 ,后序遍历 , 中序遍历的问题
- java同步锁-实现买火车票
- XMU C语言程序设计实践(3)
- 小波折发现热部署
- iOS手写签名生成图片<贝赛尔曲线>
- Linux 命令代换反引号和$()