【leetcode】4. Median of Two Sorted Arrays
计算中间两个数的平均值
没被hard难住,这题就是归并排序的应用,注意空指针
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int length = length(nums1) + length(nums2); boolean isOdd = (length & 1) == 1; int left = 0; int right = 0; int middleRight = length / 2; int middleLeft = isOdd ? middleRight : middleRight - 1; int middleLeftValue = 0; int middleRightValue = 0; for (int i = 0; i <= middleRight && i < length; ++i) { int leftValue = get(nums1, left); int rightValue = get(nums2, right); if (leftValue <= rightValue) { left++; if (i == middleLeft) { middleLeftValue = leftValue; } if (i == middleRight) { middleRightValue = leftValue; } } else { right++; if (i == middleLeft) { middleLeftValue = rightValue; } if (i == middleRight) { middleRightValue = rightValue; } } } return (middleLeftValue + middleRightValue) * 1.0 / 2; } private int length(int[] num) { return num == null ? 0 : num.length; } private int get(int[] nums, int index) { if (nums == null || index >= nums.length) { return Integer.MAX_VALUE; } else { return nums[index]; } } }