力扣 #4 尋找兩個正序陣列的中位數
阿新 • • 發佈:2020-12-06
方法一 函式庫合併 毫無技術含量 不講了
1 class Solution { 2 public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 int[] c= new int[nums1.length+nums2.length]; 4 System.arraycopy(nums1, 0, c, 0, nums1.length); 5 System.arraycopy(nums2, 0, c, nums1.length, nums2.length); 6 Arrays.sort(c);7 double res = 0; 8 if(c.length %2 == 1){ 9 res = c[c.length/2]; 10 }else{ 11 res += c[c.length/2]; 12 res += c[c.length/2 - 1]; 13 res = res/2; 14 } 15 return res; 16 } 17 }
方法二 其實求中位數 只需要知道中位數的位置在哪個陣列哪個位置就好了 也就是拿每個陣列最開頭的位置依次進行比較
哪個陣列的位置數字最小 就把比較的位置向前移一位 然後繼續比較 直到比較到 總長度/2 次為止
1 class Solution { 2 public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 int len1 = nums1.length; 4 int len2 = nums2.length; 5 int len = len1 + len2; 6 7 double left = -1, right = -1; 8 intastart = 0, bstart = 0; 9 10 for(int i = 0; i <= len / 2; i++){ 11 left = right; 12 //這裡比較巧妙的是把一個數組走到頭另一個數組沒走到頭的情況考慮到了 這種情況只需要在另一個數組移動剩下的步數即可 13 if(astart < len1 && (bstart >= len2 || nums1[astart] < nums2[bstart])){ 14 right = nums1[astart++]; 15 }else{ 16 right = nums2[bstart++]; 17 } 18 } 19 if((len & 1) == 1) return right; 20 else return (left + right) / 2; 21 } 22 }
O(log (m+n))時間複雜度的話 需要用到二分 力扣裡有具體實現 摸魚溜了