面試10大演算法題彙總 字串和陣列3

2021-06-28 22:22:19 字數 876 閱讀 2818

5.求兩個有序陣列的中位數

有兩個有序陣列a和b,其大小分別為m和n,求兩個有序數的中間值

若m+n為偶數,則求兩個中間數的平均值。

例:a = ;

b = ;

output:5.0

a = ;

b = ;

output:3.0

要求時間複雜度為o(log(m+n))

由於對時間複雜度有要求,因此不能直接遍歷,可考慮分治法

假設陣列a的中位數為m1,陣列b為m2,例如:

ar1 =

ar2 =

m1 = 12 ,m2 = 17 。由於m1[12,15] 和 [2, 13, 17]

重複這個步驟,可以得到   m1 = 15  m2 = 13.得到兩個子陣列:

[12, 15] 和[13, 17]

這時,由於n=2,無法在繼續分下去了。可以直接計算得:

(13 + 15) / 2 = 14.0

code:

public class test 

} public static int findkth(int a, int b, int k, int astart, int aend,

int bstart, int bend) else

return findkth(a, b, k, astart, aend, bstart, bend);

} public static void main(string args) ;

int b = ;

double c = findmediansortedarrays(a, b);

system.out.println(c);

}}

php 面試 10大演算法題

functionm order arr return arr var dump m order 1,3,2,5,7,9 die 優化氣泡排序 function m order arr for h 0 h count 1 h if flag 0 return arr var dump m order ...

DP字串型別題彙總

最長公共子串 lcs 輸出a和b最長公共子串的長度,並列印結果 include using namespace std const int maxn 1005 int d maxn maxn char a maxn b maxn int la,lb intmain int len d la lb p...

字串和數字相關演算法

1 比較版本號 比較兩個版本號 version1 和 version2。如果 version1 version2 返回 1,如果 version1 version2 返回 1,除此之外返回 0。public class threesum 兩個字串比較版本 private static int com...