#4 Median of Two Sorted Arrays
来源:互联网 发布:网络被劫持怎么办 编辑:程序博客网 时间:2024/05/29 08:03
题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/
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)).
int Min(int a, int b) { return a < b ? a : b;}int FindKth(int *nums1, int n1, int *nums2, int n2, int k) { //返回两个数组第k小的数,递归实现 int pa = Min(n1, k / 2), pb = k - pa; //pa,pb分别指向两个数组的第k/2个元素,数组一小于k/2个时pa指向最后一个元素 if(n2 < n1) //确保第一个数组短于第二个数组 return FindKth(nums2, n2, nums1, n1, k); if(n1 == 0) //基准情况,第一个数组为空时直接返回第二个数组中第k个元素 return nums2[k - 1]; if(k == 1) return Min(nums1[0], nums2[0]); //基准情况,k = 1时无法递归至上一基准情况;直接返回头结点的较小节点 if(nums1[pa - 1] < nums2[pb - 1]) { //数组一中的第K/2个元素小于数组二中的第K/2个元素,说明小于数组一中第k/2个元素元素个数少于k个,即第k小的元素一定不在数组一中的前k/2个元素;递归查找数组一余下部分和数组二 return FindKth(nums1 + pa, n1 - pa, nums2, n2, k - pa); } else if(nums1[pa - 1] > nums2[pb - 1]) { return FindKth(nums1, n1, nums2 + pb, n2 - pb, k - pb); } else { return nums1[pa - 1]; }}double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int k = (nums1Size + nums2Size) / 2; if((nums1Size + nums2Size) % 2 == 1) //总数为奇数,返回第k个(k为总数一半) return FindKth(nums1, nums1Size, nums2, nums2Size, k + 1); else //总数为偶数,返回第k、第k+1个的平均数 return (FindKth(nums1, nums1Size, nums2, nums2Size, k) + FindKth(nums1, nums1Size, nums2, nums2Size, k + 1)) / 2.0;}
0 0
- Leetcode 4 Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [leetcode 4] Median of Two Sorted Arrays
- LeetCode 4:《Median of Two Sorted Arrays》
- [Leetcode] 4 - Median of Two Sorted Arrays
- 4、Median of Two Sorted Arrays
- leetcode|4|Median of Two Sorted Arrays
- 4,Median of Two Sorted Arrays
- [Leetcode]4Median of Two Sorted Arrays
- leetcode 4 Median of Two Sorted Arrays
- 4 Median of Two Sorted Arrays
- LeetCode #4 Median of Two Sorted Arrays
- LeetCode-4-Median of Two Sorted Arrays
- LeetCode 4 Median of Two Sorted Arrays
- leetcode 4 Median of Two Sorted Arrays
- 4 Median of Two Sorted Arrays
- Java的auto-boxing与对象实例的比较
- RCP开发浅谈之SWT,JFACE
- Java JDBC连接MYSQL数据库教程
- Effetive C++ 条款4
- Lua 与C/C++ 交互系列:通过C++调用Lua函数(2)
- #4 Median of Two Sorted Arrays
- jQuery.extend和jQuery.fn.extend的区别
- c_str函数
- 黑马程序员--JAVA学习笔记第六天
- 创建一个简单的输入表单
- Swift之旅:2.完成计算器,初探MVC设计模式
- 写入 删除 沙河文件
- 工厂模式
- Activity 与Servlet的相似性和区别