力扣 #4 寻找两个正序数组的中位数
方法一 函数库合并 毫无技术含量 不讲了
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 int astart = 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))时间复杂度的话 需要用到二分 力扣里有具体实现 摸鱼溜了

浙公网安备 33010602011771号