zoukankan      html  css  js  c++  java
  • LeetCode OJ 4. 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)).

    Example 1:

    nums1 = [1, 3]
    nums2 = [2]
    
    The median is 2.0

    Example 2:

    nums1 = [1, 2]
    nums2 = [3, 4]
    
    The median is (2 + 3)/2 = 2.5

    Subscribe to see which companies asked this question


    【题目分析】

    给定两个升序排列的整数数组,找到这两个数组所有元素的中位数。


    【思路】


    【java代码】

     1 public class Solution {
     2     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
     3         int[] A = nums1, B = nums2;
     4         int m = nums1.length, n = nums2.length;
     5         
     6         if(m > n){
     7             A = nums2; B = nums1;
     8             m = nums2.length; n = nums1.length;
     9         }
    10         
    11         if(n == 0) return 0;
    12         
    13         int mini = 0, maxi = m;
    14         int i = 0, j = 0;
    15         int maxofleft, minofright = 0;
    16         
    17         while(mini <= maxi){
    18             i = (maxi - mini)/2 + mini;
    19             j = (m + n + 1)/2 - i;
    20             if(j > 0 && i < m && B[j-1] > A[i]){
    21                 mini = i + 1;
    22             }   //i is too small
    23             else if(i > 0 && j < n && A[i-1] > B[j]){
    24                 maxi = i - 1;
    25             }   //i is too big
    26             else{
    27                 if(i == 0) maxofleft = B[j-1];
    28                 else if(j == 0) maxofleft = A[i-1];
    29                 else maxofleft = Math.max(A[i-1], B[j-1]);
    30                 
    31                 if((m + n)%2 == 1) return maxofleft;
    32                 
    33                 if(i == m) minofright = B[j];
    34                 else if(j == n) minofright = A[i];
    35                 else minofright = Math.min(B[j], A[i]);
    36                 
    37                 return (double)(maxofleft + minofright) / 2.0;
    38             }
    39         }
    40         return 0;
    41     }
    42 }
  • 相关阅读:
    小程序游戏如何接入支付呢?
    手机回复小程序客服消息
    小程序客服发送卡片消息
    小程序多客服对应售前售后,或者不同的客服人员
    php 7 event 安装
    workerman相关
    树莓派:你是我的眼
    Python应用03 使用PyQT制作视频播放器
    从写博到出书:过程全记录
    协议森林17 我和你的悄悄话 (SSL/TLS协议)
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5808722.html
Copyright © 2011-2022 走看看