[Leetcode]Median of two sorted array
来源:互联网 发布:龙珠gt战斗力官方数据 编辑:程序博客网 时间:2024/05/16 14:17
[题目]
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)).
[分析]
[code] from nineChapter
public double findMedianSortedArrays(int A[], int B[]) { int len = A.length + B.length; //AB一起总共的长度 if (len % 2 == 0) { //如果总长度是偶数 return (findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)) / 2.0 ; //那么分表找A,B 的中前长度值和中后长度值,然后取中间 } else { return findKth(A, 0, B, 0, len / 2 + 1); //如果直接是奇数的,那么直接返回中间值就好了。 } } // find kth number of two sorted array public static int findKth(int[] A, int A_start, int[] B, int B_start, int k){if(A_start >= A.length) //如果A的起始已经大于A 的总长度了,那么直接返回B的开始 + k -1位置的值return B[B_start + k - 1]; if(B_start >= B.length) //同理,对于B,加入已经到头了,return A[A_start + k - 1];//返回A开始的位置加k.if (k == 1) //如果k==1,return Math.min(A[A_start], B[B_start]);//返回A,B开头最大的那个int A_key = A_start + k / 2 - 1 < A.length ? A[A_start + k / 2 - 1] : Integer.MAX_VALUE;int B_key = B_start + k / 2 - 1 < B.length ? B[B_start + k / 2 - 1] : Integer.MAX_VALUE; if (A_key < B_key) { //如果A的值小于B,搜索A的后半部分,对于B不用动,整体长度减半return findKth(A, A_start + k / 2, B, B_start, k - k / 2);} else {return findKth(A, A_start, B, B_start + k / 2, k - k / 2);}}
0 0
- LeetCode 4: Median Of Two Sorted Array
- Leetcode - Median of Two Sorted Array
- Median of Two Sorted Array---LeetCode
- [leetcode] #4 Median of Two Sorted Array
- LeetCode:Median of two sorted array
- Leetcode--Median of Two Sorted Array
- [Leetcode]Median of two sorted array
- [LeetCode]Median of Two Sorted Array
- Median of Two Sorted Array leetcode java
- Median of Two Sorted Array leetcode java
- Median of Two Sorted Array
- Median of two sorted array
- median of two sorted array
- median of two sorted array
- Median of two sorted array
- leetcode.array--4. Median of Two Sorted Arrays
- LeetCode-Median of sorted array
- LeetCode2: Median of Two sorted array.
- OpenCV进阶之路:神经网络识别车牌字符
- 【EMGU】读取视频AVI文件+保存任意帧为图片
- sp_pv_channel_portfolio_manager_dtl
- Linux Python 多版本管理
- POJ - 1325 Machine Schedule 二分图 最小点覆盖
- [Leetcode]Median of two sorted array
- 一种巧妙的设计--通过继承扩展接口
- PHP获取当月开始与结束的时间戳
- mysql error: The user specified as a definer ('mysqladmin'@'localhost') does not exist
- python学习笔记
- Spring+Quartz整合
- C# Winform DataGridView 全选
- Python基础教程笔记——条件,循环和其他语句
- Leetcode--SortColors