博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Median of Two Sorted Arrays. java.
阅读量:7238 次
发布时间:2019-06-29

本文共 1181 字,大约阅读时间需要 3 分钟。

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)).

public class Solution {    public double findMedianSortedArrays(int A[], int B[]) {        int k = A.length + B.length;        return k % 2 == 0 ?  (findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1) +         findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2)) / 2        : findK(A, 0, A.length - 1, B, 0, B.length - 1, k/2 + 1);    }    //返回两个数组中第k大的元素。    public double findK(int a[], int s1, int e1, int b[], int s2, int e2, int k) {        int m = e1 - s1 + 1;        int n = e2 - s2 + 1;        if (m > n) return findK(b, s2, e2, a, s1, e1, k); //a的长度比b的小。

if (s1 > e1) return b[s2 + k - 1]; if (s2 > e2) return a[s1 + k - 1]; if (k == 1) return Math.min(a[s1], b[s2]); int midA = Math.min(k/2, m), midB = k - midA; //假设a的第midA大的元素比b的第midB大的元素小, //那么删掉a的前midA个元素,在剩余的数中找第k-midA大的。 if (a[s1 + midA - 1] < b[s2 + midB - 1]) return findK(a, s1 + midA, e1, b, s2, e2, k - midA); else if (a[s1 + midA - 1] > b[s2 + midB - 1]) return findK(a, s1, e1, b, s2 + midB, e2, k - midB); else return a[s1 + midA - 1]; } }

转载地址:http://uorfm.baihongyu.com/

你可能感兴趣的文章
React-Router看这里
查看>>
打造一个通用的 RecyclerView Adapter
查看>>
基于redis的秒杀
查看>>
js如何实现上拉加载更多...
查看>>
.Net Core Logger 实现log写入本地文件系统
查看>>
Java Servlet关键点详解
查看>>
深入分析luait反编译之luajit-decomp
查看>>
从头编写 asp.net core 2.0 web api 基础框架 (5) EF CRUD
查看>>
【我们一起写框架】MVVM的WPF框架(五)—完结篇
查看>>
学习ASP.NET Core Razor 编程系列十一——把新字段更新到数据库
查看>>
江山代有才人出 | 微软亚洲研究院建院二十周年
查看>>
Linux安装gitlab
查看>>
java源码-synchronized
查看>>
PostgreSQL 10.1 手册_部分 III. 服务器管理_第 21 章 数据库角色_21.2. 角色属性
查看>>
《刻意练习》读后感
查看>>
DataWorks V2.0 系列公开课
查看>>
使用 logstash, elasticsearch, kibana 搭建日志分析系统
查看>>
Android Q 将获得大量的隐私保护功能
查看>>
《恋恋笔记本》观后感
查看>>
Spring源码剖析6:Spring AOP概述
查看>>