2020-09-01 尋找兩個(gè)正序數(shù)組的中位數(shù)

題目:

給定兩個(gè)大小為 m 和 n 的正序(從小到大)數(shù)組?nums1 和?nums2。

請(qǐng)你找出這兩個(gè)正序數(shù)組的中位數(shù),并且要求算法的時(shí)間復(fù)雜度為?O(log(m + n))。

你可以假設(shè)?nums1?和?nums2?不會(huì)同時(shí)為空。

示例 1:

nums1 = [1, 3]

nums2 = [2]

則中位數(shù)是 2.0

示例 2:

nums1 = [1, 2]

nums2 = [3, 4]

則中位數(shù)是 (2 + 3)/2 = 2.5


思路:

將數(shù)組元素合并到list,對(duì)list排序取中間元素


方法:

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {

double result;

? ? // 將兩個(gè)數(shù)組元素裝進(jìn)list

? ? List list =new ArrayList<>();

? ? for (int i : nums1) {

list.add(i);

? ? }

for (int i : nums2) {

list.add(i);

? ? }

// 對(duì)list元素排序

? ? List collect = list.stream().sorted().collect(Collectors.toList());

? ? // 判斷l(xiāng)ist元素個(gè)數(shù)是奇數(shù)還是偶數(shù),奇數(shù)直接取中間元素,偶數(shù)取中間兩元素取平均值

? ? int size = collect.size();

? ? if (size %2 ==0) {

int a = collect.get(size /2 -1);

? ? ? ? int b = collect.get(size /2);

? ? ? ? result = (a + b) /2.0;

? ? }else {

int index = (size +1) /2 -1;

? ? ? ? result = collect.get(index);

? ? }

return result;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容