leetcode: 4. Median of Two Sorted Arrays (java)
来源:互联网 发布:华为 媒体算法工程师 编辑:程序博客网 时间:2024/06/08 13:13
题目链接:https://leetcode.com/problems/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)).
解析:一开始采用了归并排序的思想来解这道题,思想简单,但是复杂度为O(m+n);
后来借鉴了别人的思路:http://blog.csdn.net/linhuanmars/article/details/19905515
java 代码实现:
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length = nums1.length + nums2.length;
if (length%2 == 1){
return recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2 + 1);
} else {
return (recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2)+recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2 + 1))/2.0;
}
}
public double recrusive(int[] A, int[] B, int i, int i2, int j, int j2, int k){
int m = i2-i+1;
int n = j2-j+1;
if (m > n) return recrusive(B, A, j, j2, i, i2, k);
if (m == 0) {
return B[j+k-1];
}
if (k == 1){
return Math.min(A[i], B[j]);
}
int posA = Math.min(k/2, m);
int posB = k-posA;
if(A[i+posA-1] == B[j+posB-1]){
return A[i+posA-1];
}else if (A[i+posA-1] < B[j+posB-1]){
return recrusive(A, B, i+posA, i2, j, j+posB-1, k-posA);
}else {
return recrusive(A, B, i, i+posA-1, j+posB, j2, k-posB);
}
}
}
- [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 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- 一个golang推送服务器集群:gopush-cluster
- App 版本信息等
- 重装win7后ubuntu系统没有了,如何找回ubuntu系统
- c语言external变量的使用
- 最后的战役——择业总攻。
- leetcode: 4. Median of Two Sorted Arrays (java)
- ImageIoader 加载图片与PhotoView图片缩放
- 求解大型 COMSOL 模型需要多少内存?
- Hive文件格式
- leetcode 34. Search for a Range
- 洋葱炒蛋 && 蒜苔炒肉
- leetcode题解日练--2016.6.18
- js中容易被忽视的事件问题总结
- NodeMCU文档中文翻译 5 上传代码