Leetcode 4 Median of Two Sorted Arrays Java
来源:互联网 发布:高校法学教学软件 编辑:程序博客网 时间:2024/06/01 11:18
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)).
这道题目看似比较简单,做起来才发现暗藏玄机。。。。
这道题的一种思路,将题目转换为寻找第k小的值的问题。
程序如下:
public double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; int total = m+n; if ((total&1) == 1) return findKth(A, 0, m, B, 0, n, total/2+1); else return (findKth(A, 0, m, B, 0, n, total/2) + findKth(A, 0, m, B, 0, n, total/2+1))/2; } public double findKth(int a[], int startA, int m, int b[], int startB, int n, int k) { if (m > n) return findKth(b, startB, n, a, startA, m, k); if (m == 0) return b[startB + k-1]; if (k == 1) return min(a[startA], b[startB]); int pa = min(k/2, m), pb = k - pa; if (a[startA + pa-1] < b[startB + pb-1]) return findKth(a, startA + pa, m-pa, b, startB, n, k - pa); else return findKth(a, startA, m, b, startB + pb, n-pb, k-pb); } private int min(int a, int b){ return a > b ? b : a; }
0 0
- [Leetcode] Median of Two Sorted Arrays (Java)
- [LeetCode][Java] Median of Two Sorted Arrays
- Median of Two Sorted Arrays --leetcode java
- LeetCode : Median of Two Sorted Arrays [java]
- leetcode:Median of Two Sorted Arrays 【Java】
- [LeetCode]Median of Two Sorted Arrays(Java)
- leetcode Median of Two Sorted Arrays(Java)
- Leetcode-Median of Two Sorted Arrays (java)
- 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]4Median of Two Sorted Arrays
- leetcode 4 Median of Two Sorted Arrays
- Struts2学习笔记(十四)Annotation实现Struts2的配置
- rails 单表继承 观察者
- [Android] Intent 传递对象
- 第八周项目-1.1
- 线性表的线性存储及基本操作
- Leetcode 4 Median of Two Sorted Arrays Java
- ActiveRecord 验证及回调函数callback
- 文本纠错项目一些问题
- yum安装Tomcat
- 获取硬件UUID方法(windows、linux)
- Android多线程断点下载
- 开始学习quick 3.5注意
- 简单的AT NEW 和 COLLECT的实现方式
- 关于IMCart开源商城系统