leetcode 之Median of Two Sorted Arrays(五)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 之Median of Two Sorted Arrays(五)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? ?? ?找兩個排好序的數組的中間值,實際上可以擴展為尋找第k大的數組值。
? ? ? ? ? ? ? ? 參考下面的思路,非常的清晰:
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? 代碼:
? ? ? ? ? ? ? ? ? ? ? ? ? ??
double findMedianofTwoSortArrays(int A[], int B[], int m, int n){int total = m + n;//判斷序列長度的奇偶,奇數只有一個中間值,偶數有兩個中間值,取平均if (total & 0x1)return find_kth(A, m, B, n, total / 2 + 1);elsereturn (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n, total / 2 + 1)) / 2;}int find_kth(int A[], int m, int B[], int n, int k){//設定m<=nif (m > n)return find_kth(B, n, A, m, k);if (m == 0)return B[k - 1];if (k == 1)return min(A[0], B[0]);//刪除掉一部分數據int ia = min(k / 2, m), ib = k - ia;if (A[ia - 1] < B[ib - 1])return find_kth(A + ia, m - ia, B, n, k - ia);else if (A[ia - 1]>B[ib - 1])return find_kth(A, m, B + ib, m - ib, k - ib);elsereturn A[ia - 1];} View Code?
轉載于:https://www.cnblogs.com/573177885qq/p/5492407.html
總結
以上是生活随笔為你收集整理的leetcode 之Median of Two Sorted Arrays(五)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 股市八大机构是哪八大
- 下一篇: IntelliJ Idea工具使用