zoukankan      html  css  js  c++  java
  • Leetcode 5——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)).

     1 Example 1:
     2 nums1 = [1, 3]
     3 nums2 = [2]
     4 
     5 The median is 2.0
     6 Example 2:
     7 nums1 = [1, 2]
     8 nums2 = [3, 4]
     9 
    10 The median is (2 + 3)/2 = 2.5

      即找两个有序数组的中位数,一开始想的是用第三个数组来把前面两个数组的值依次放进去,再直接找中间的数,但是对时间复杂度的要求是O(log (m+n)),所以不能用数组存。网上找的方法是比较两个数组中间的元素,如AB两个数组,如果A[mid]>B[mid],那中位数肯定就不在B的前半段,于是缩小了范围,即B后半段加上A,然后依次查找并缩小范围,直到找到中间的数为止。

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            
            int m=nums1.length;
            int n=nums2.length;
            if((m+n)%2==0)
                return (findKMax((m+n)/2,nums1,0,nums2,0)+findKMax((m+n)/2+1,nums1,0,nums2,0))/2.0;//如果是偶数
            else 
                return findKMax((m+n)/2+1,nums1,0,nums2,0);//如果是奇数
        }
        public int findKMax(int k,int[] nums1,int start1,int[] nums2,int start2){
            if(start1>=nums1.length)//第一个数组长度为0的话,直接返回第二个数组的中位数
                return nums2[start2+k-1];
                
            if(start2>=nums2.length)//第二个数组长度为0的话,直接返回第一个数组的中位数
                return nums1[start1+k-1];
            
            if(k==1)//k=1,即找第一个,也就是nums1或nums2中最小的
                return Math.min(nums1[start1], nums2[start2]);
                
            int temp1=start1+k/2-1;
            int temp2=start2+k/2-1;
            
            int mid1=temp1<nums1.length?nums1[temp1]:Integer.MAX_VALUE;//nums1没有下标为temp1的元素,如果有,就用那个元素比较,没有就用最大int
            int mid2=temp2<nums2.length?nums2[temp2]:Integer.MAX_VALUE;
    
            if(mid1>=mid2)
                return findKMax(k-k/2,nums1,start1,nums2,temp2+1);//如果mid1大,也就是nums1中间的数大,那么nums1前半段不会有中位数
            else                                                  //从nums1后半段和nums1开始找
                return findKMax(k-k/2,nums1,temp1+1,nums2,start2);
                
            
        }
        
        
    }
  • 相关阅读:
    tensorflow入门(三)
    tensorflow入门(二)
    setTimeout
    PreResultListener
    sql 删除重复记录
    oracle dual表用途及结构详解
    oracle中的dual表
    Dubbo远程调用服务框架原理与示例
    struts2和spring的两种整合方式
    Timer和TimerTask详解
  • 原文地址:https://www.cnblogs.com/GoForMyDream/p/6422456.html
Copyright © 2011-2022 走看看