leetcode 4. Median of Two Sorted Arrays (java)
Posted eniac-inner
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 4. Median of Two Sorted Arrays (java)相关的知识,希望对你有一定的参考价值。
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; if (len1 == 0 && len2 == 0) return 0; if (len2 < len1) { int[] temp = nums2; nums2 = nums1; nums1 = temp; len1 = nums1.length; len2 = nums2.length; } int half = (len1 + len2 + 1) / 2; boolean even = ((len1 + len2) % 2) == 0 ? true : false; int start = 0; int end = len1; int apart = 0; int bpart = 0; while (start <= end) { apart = (start + end) / 2; bpart = half - apart; if (apart > start && nums1[apart - 1] > nums2[bpart]) end = apart - 1; else if (apart < end && nums1[apart] < nums2[bpart - 1]) start = apart + 1; else { int leftmax = 0; if (apart == 0) leftmax = nums2[bpart - 1]; else if (bpart == 0) leftmax = nums1[apart - 1]; else { leftmax = Math.max(nums1[apart - 1], nums2[bpart - 1]); } if (!even) return leftmax; int minRight = 0; if (apart == len1) minRight = nums2[bpart]; else if (bpart == len2) minRight = nums1[apart]; else { minRight = Math.min(nums2[bpart], nums1[apart]); } return (leftmax + minRight) / 2.0; } } return 0; } } //时间复杂度: O(log(min(m, n))) //空间复杂度: O(1)
以上是关于leetcode 4. Median of Two Sorted Arrays (java)的主要内容,如果未能解决你的问题,请参考以下文章
4. 两个有序数组的中值 [leetcode 4: Median of Two Sorted Arrays]
4. 两个有序数组的中值 [leetcode 4: Median of Two Sorted Arrays]
leetcode-4 Median of Two Sorted Arrays
leetcode-4-Median of Two Sorted Arrays