004_LeetCode_4 Median of Two Sorted Arrays 题解
来源:互联网 发布:linux的service命令 编辑:程序博客网 时间:2024/06/05 15:36
Description
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.0
Example 2:
nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
解:
假设nums1的长度小于nums2的长度:
以i将nums1划分为两部分nums1_l和nums1_r,同时有
r=m+n+12 将nums2划分为两部分nums2_l和nums2_r划分之后,将两个数组对应的左右部分分别对应,如下表:
当满足以下两个条件时:
i+j=m−i+n−j nums2[j−1]≤nums1[i] andnums1[i−1]≤nums2[j]
可以得到中值:
- 若
m+n 为奇数,中值为:max(nums1[i−1],nums2[j−1]) - 否则,中值为:
max(nums1[i−1],nums2[j−1])+min(nums1[i],nums2[j])2
Java代码:
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length, n = nums2.length; // 确保n大于m if (m > n) { int[] temp = nums1; nums1 = nums2; nums2 = temp; int tmp = m; m = n; n = tmp; } int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2; while (iMin <= iMax) { int i = (iMin + iMax) / 2; int j = halfLen - i; if (i < iMax && nums2[j-1] > nums1[i]){ // i的值太小 iMin = iMin + 1; } else if (i > iMin && nums1[i-1] > nums2[j]) { // i的值太大 iMax = iMax - 1; } else { int maxLeft = 0; // 计算左半部分的最大值 if (i == 0) { maxLeft = nums2[j-1]; } else if (j == 0) { maxLeft = nums1[i-1]; } else { maxLeft = Math.max(nums1[i-1], nums2[j-1]); } // 两个数组的长度之和为奇数时,中值为长度的中间值 if ( (m + n) % 2 == 1 ) { return maxLeft; } // 当两个数组的长度之和为偶数时, 中值等于左半部分的最大值与右半部分的最小值的均值 int minRight = 0; if (i == m) { minRight = nums2[j]; } else if (j == n) { minRight = nums1[i]; } else { minRight = Math.min(nums2[j], nums1[i]); } return (maxLeft + minRight) / 2.0; } } return 0.0; }}
阅读全文
0 0
- 004_LeetCode_4 Median of Two Sorted Arrays 题解
- [LeetCode题解004]Median of Two Sorted Arrays
- [Leetcode题解]004 Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- [LeetCode]-004-Median of Two Sorted Arrays
- 004Median of Two Sorted Arrays
- 004 Median of Two Sorted Arrays [Leetcode]
- 004 - Median of Two Sorted Arrays
- [LeetCode]004-Median of Two Sorted Arrays
- 004Median of Two Sorted Arrays (C)
- Leetcode 004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays *
- leetcode-004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays
- 004 Median of Two Sorted Arrays ⭐
- LeetCode-004 Median of Two Sorted Arrays
- leetcode 004 Median of Two Sorted Arrays
- LeetCode 题解(66): Median of Two Sorted Arrays
- 回溯——用蒙特卡洛算法估计回溯算法的效率
- SVN的学习之路一(体系结构)
- 無需Google Home!手機可控制谷歌電視棒
- 设置好看的eclipse界面
- java web调用mapreduce算法-Day2&4(更新)
- 004_LeetCode_4 Median of Two Sorted Arrays 题解
- java通过jdbc访问oracle数据库的存储过程和存储函数
- 2017.10.15开学第七周周总结
- JS中使用cookie
- 1035. Password (20)
- tree standings 树 && dp
- 第四周项目一 建立单链表
- 任务调度器和异步执行器
- Function的含义