leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
来源:互联网 发布:评价李鸿章 知乎 编辑:程序博客网 时间:2024/05/16 19:41
There are two sorted arrays A and B 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)).
存在两个已排序数组AB,要求找到这两个数组的中位数,要求时间复杂度O(log (m+n)).
拿到这道题如果不考虑时间复杂度,首先我们想到的是将这两个字符串合并成一个已排序的字符串,length = (m+n)/2 如果length是奇数直接返回总字符串的第(m+n)/2位,如果为偶数返回中间两位的平均数。
但这种方法需要做一次排序,进一步优化,想通过定义两个指针一次查找这两个数组到第length/2次结束,分别找到第length/2 和 length/2-1位。代码实现如下:
public class FindMedianSortedArrays { public static void main(String[] args){ int[] A = new int[]{}; int[] B = new int[]{2,3}; System.out.print(findMedianSortedArrays(A,B)); } public static double findMedianSortedArrays(int A[], int B[]) { if(A==null && B==null) return 0; // 限定AB都不能为0 int m=0,n=0; // 存储AB的长度 double k=0,preK=0; // 存放length/2 以及 length/2-1 位的数字 int length = 0; // 存放整体长度 if(A==null) m=0; else m = A.length; // 对mn赋值 if (B==null) n=0; else n = B.length; length = m+n; // 对length赋值 if(length<2){ // 如果AB中一个长度为0 另一个为1则直接返回 if(m==0) return B[0]; else return A[0]; } int count = 0; int i=0,j=0; if(m==0){ // 只有B存在,A的长度为0,直接返回B的中位数 if (length%2==0){ return ((double)B[length/2]+(double)B[length/2-1])/2; }else return B[length/2]; }else{ if (n==0){ // 只有a存在 if (length%2==0){ return ((double)A[length/2]+(double)A[length/2-1])/2; }else return A[length/2]; } } while (count<=length/2){ // 都存在时从头遍历,找到中间及其之前的一位数 if((i<m && j<n && A[i]<=B[j])||(j>=n)){ preK = k; k = A[i]; ++i; }else{ if((i<m && j<n && A[i]>B[j])||(i>=m)){ preK = k; k = B[j]; ++j; } } ++count; } if (length%2 == 1){ return k; }else { return (k+preK)/2; } }}
0 0
- leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
- leetcode解题之4. Median of Two Sorted Arrays java (两个排序数组的中位数)
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 两个有序数组的中位数 Median of Two Sorted Arrays
- Median of Two Sorted Arrays 两个数组的中位数
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- 【数组】两个排序数组的中位数Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays,找出两个排好序的数组的中位数
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- LeetCode | Median of Two Sorted Arrays(两个数组的中位数)
- LeetCode OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- LeetCode 4. Median of Two Sorted Arrays(两个有序数组的中位数)
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- 4.leetcode Median of Two Sorted Arrays(medium)[求两个数组的中位数]
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- LeetCode OJ:Median of Two Sorted Arrays(两个有序数组的中位数)
- js 操作 文件
- iOS开发之----动态类型(isKindOfClass, isMemberOfClass,id)等
- HTTP协议详解
- 索引优先队列的实现
- TableViewCell分割线的设置
- leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
- 2015年1月17日,我的HTML笔记。
- Object C 中协议使用详解
- 文件上传
- cocos2dx-3.0(23) ScrollView 缩放 及 touch新用法
- Opengl ES 1.x NDK实例开发之八:旋转的纹理金字塔
- 网易云课堂程序设计入门—Java语言(第四周)
- 数据结构C++版 绪论
- java ... and :