[LeetCode-JAVA] Median of Two Sorted Arrays

來源:互聯網
上載者:User

標籤:

題目:

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

思路:題目大意是找到兩個數組的中位元,查了下相關定義,計算有限個數的資料的中位元的方法是:把所有的同質資料按照大小的順序排列。如果資料的個數是奇數,則中間那個資料就是這群資料的中位元;如果資料的個數是偶數,則中間那2個資料的算術平均值就是這群資料的中位元。

分享下網上很簡潔思路的演算法,找兩個數組中第k小元素,該方法的核心是將原問題轉變成一個尋找第k小數的問題(假設兩個原序列升序排列),這樣中位元實際上是第(m+n)/2小的數。所以只要解決了第k小數的問題,原問題也得以解決。

首先假設數組A和B的元素個數都大於k/2,我們比較A[k/2-1]和B[k/2-1]兩個元素,這兩個元素分別表示A的第k/2小的元素和B的第k/2小的元素。這兩個元素比較共有三種情況:>、<和=。如果A[k/2-1]<B[k/2-1],這表示A[0]到A[k/2-1]的元素都在A和B合并之後的前k小的元素中。換句話說,A[k/2-1]不可能大於兩數組合并之後的第k小值,所以我們可以將其拋棄。

 

代碼:

public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int len1 = nums1.length;        int len2 = nums2.length;        int total = len1 + len2;        if(total % 2 == 1)            return findKth(nums1, 0, len1-1, nums2, 0, len2-1, total/2+1);        else            return (findKth(nums1, 0, len1-1, nums2, 0, len2-1, total/2)                     + findKth(nums1, 0, len1-1, nums2, 0, len2-1, total/2+1)) / 2;    }        public double findKth(int[] a, int astart, int aend, int[] b, int bstart, int bend, int k){        int m = aend - astart + 1;        int n = bend - bstart + 1;        if(m > n)  //時刻保持a為最短 方便後續判斷            return findKth(b, bstart, bend, a, astart, aend, k);        if(m == 0)  //當有一個數組為空白時              return b[bstart + k-1];  // 第k小的        if(k == 1) //找最小的            return Math.min(a[astart], b[bstart]);                    int da = Math.min(k/2, m);   //當m的長度不足k時,需要整個的a數組        int db = k - da;                if(a[astart + da - 1] < b[bstart + db - 1]){            return findKth(a, astart+da, aend, b, bstart, bend, k - da);        }else if(a[astart + da - 1] > b[bstart + db - 1]){            return findKth(a, astart, aend, b, bstart+db, bend, k - db);        }else{            return a[astart + da - 1];        }    }}

參考連結: http://blog.csdn.net/yutianzuijin/article/details/11499917/

      http://www.cnblogs.com/springfor/p/3861890.html

[LeetCode-JAVA] Median of Two Sorted Arrays

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.