1. 程式人生 > >LeetCode題目----求中位數---標簽:Array

LeetCode題目----求中位數---標簽:Array

變量 linked int i++ n) 大小 給定 png color

題目難度---困難

題目要求:

給定兩個大小為 m 和 n 的有序數組 nums1 和 nums2 。

請找出這兩個有序數組的中位數。要求算法的時間復雜度為 O(log (m+n)) 。

思路:第一眼看到題目兩個數組求中位數,看似很復雜,但是仔細一想,兩個數組合在一塊不久行了?然後合並後的數組給他排序,進而判斷是奇數位數組還是偶數位數組

ok!代碼奉上:

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] result = new int[nums1.length + nums2.length];//
首先初始化合並數組的大小 List list = new LinkedList();// 建立新數組,目的是list集合插入方便 if (result.length == 0) {// 判斷數組是否為空 return 0; } // 將兩個數組中的值放入list集合中 for (int i : nums1) { list.add(i); } for (int j : nums2) { list.add(j); }
// 這部很關鍵--因為後面遍歷整個數組排序數組會因為這部操作而大大簡化 for (int i = 0; i < list.size(); i++) { result[i] = (Integer) list.get(i);// 很簡單的將list集合的元素一個個遍歷到result數組中 } // 下面就是新數組及合並後的數組排序 for (int i = 0; i < result.length; i++) { for (int j = i + 1; j < result.length; j++) {
if (result[i] >= result[j]) { int temp = result[i]; result[i] = result[j]; result[j] = temp; } } } // -----------------這個地方就是判斷數組的元素是奇數偶數,奇數取最中間的數就可以了,偶數就中間倆位取平均了 double answer = 0; if (result.length % 2 == 1) { int q = result.length / 2; answer = result[q]; } else { int p = result.length / 2; for (int i = 0; i < result.length; i++) { if (p - 1 == i) { answer = result[i]; break; } } answer = (answer + result[p]) / 2; } // 上邊註意的地方:數組元素計算奇數偶數後取值時應註意遍歷是從0開始,因此result.length/2的值要比遍歷變量大1 return answer; }

技術分享圖片

emmmm第一篇自己寫的博客,有問題請留言……^-^

LeetCode題目----求中位數---標簽:Array