【LeetCode-面試演算法經典-Java實現】【004-Median of Two Sorted Arrays(兩個排序數組的中位元)】,leetcode--java

來源:互聯網
上載者:User

【LeetCode-面試演算法經典-Java實現】【004-Median of Two Sorted Arrays(兩個排序數組的中位元)】,leetcode--java
【004-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)).

題目大意

  兩個排序數組,找這兩個排序數組的中位元,時間複雜度為O(log(m+n))

解題思路

  採用類二分尋找演算法

代碼實現
public class Solution {    /**     * 004-Median of Two Sorted Arrays(兩個排序數組的中位元)     *     * @param nums1     * @param nums2     * @return     */    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        if (nums1 == null) {            nums1 = new int[0];        }        if (nums2 == null) {            nums2 = new int[0];        }        int len1 = nums1.length;        int len2 = nums2.length;        if (len1 < len2) {            // 確保第一個數組比第二個數組長度大            return findMedianSortedArrays(nums2, nums1);        }        // 如果長度小的數組長度為0,就返回前一個數組的中位元        if (len2 == 0) {            return (nums1[(len1 - 1) / 2] + nums1[len1 / 2]) / 2.0;        }        int lo = 0;        int hi = len2 * 2;        int mid1;        int mid2;        double l1;        double l2;        double r1;        double r2;        while (lo <= hi) {            mid2 = (lo + hi) / 2;            mid1 = len1 + len2 - mid2;            l1 = (mid1 == 0) ? Integer.MIN_VALUE : nums1[(mid1 - 1) / 2];            l2 = (mid2 == 0) ? Integer.MIN_VALUE : nums2[(mid2 - 1) / 2];            r1 = (mid1 == len1 * 2) ? Integer.MAX_VALUE : nums1[mid1 / 2];            r2 = (mid2 == len2 * 2) ? Integer.MAX_VALUE : nums2[mid2 / 2];            if (l1 > r2) {                lo = mid2 + 1;            } else if (l2 > r1) {                hi = mid2 - 1;            } else {                return (Math.max(l1, l2) + Math.min(r1, r2)) / 2;            }        }        return -1;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/46922003】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.