题目描述:
题目:Median of Two Sorted Array
描述:There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1
nums1 = [1, 3] nums2 = [2] The median is 2.0Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
分析:题目给出两个有序数组,欲求出它们合并后的中位数
我的代码:
public class Solution_4 { public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int x = len1+len2; int left=0, right=0; int i = 0, j = 0, count = 1; while(i < len1 && j < len2 && count <= x/2+1){ if(nums1[i] < nums2[j]){ left = count == x/2 ? nums1[i]:left; right = count == x/2+1 ? nums1[i]:right; i++; } else { left = count == x/2 ? nums2[j]:left; right = count == x/2+1 ? nums2[j]:right; j++; } count++; } while(i < len1 && count <= x/2+1){ left = count == x/2 ? nums1[i]:left; right = count == x/2+1 ? nums1[i]:right; i++; count++; } while(j < len2 && count <= x/2+1){ left = count == x/2 ? nums2[j]:left; right = count == x/2 + 1 ? nums2[j]:right; j++; count++; } return x % 2 == 0 ? (left+right)/2.0 : right; } public static void main(String[] args) { int[] num1 = new int[]{1,2}; int[] num2 = new int[]{3,3,3}; System.out.println(findMedianSortedArrays(num1,num2)); } }
思路分析:
用两个指针i,j分别遍历两个数组,再定义一个总的计数器count,分别用两个指针去遍历数组,同时count++,遍历到中间时候就得到了中位数