LeetCode 4---Median of Two Sorted Arrays
来源:互联网 发布:大众网络报电子版 编辑:程序博客网 时间:2024/06/12 20:47
题目链接:
转载自:http://www.lxway.com/49629084.htm
AC代码如下:、
public class Problem4 { public static void main(String[] args) { // TODO Auto-generated method stub int[] nums1={1,3}; int[] nums2={2}; System.out.println(findMedianSortedArrays(nums1,nums2)); } public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int k = m + n; if((k&1)==1) { return find(nums1, 0, m, nums2, 0, n, k/2+1); }else return (find(nums1, 0, m, nums2, 0, n, k/2)+find(nums1, 0, m, nums2, 0, n, k/2+1))/2; } //递归算法,不断缩小两个数组的范围,同时k的值也相对两个搜索区间上限起始点而改变 public static double find(int[] A, int aStart, int aEnd, int[] B, int bStart, int bEnd,int kth) { //1. 统一将长度短的放置于find函数参数的前面项 if(aEnd>bEnd) return find(B, bStart, bEnd, A, aStart, aEnd, kth); //2. 长度短的为空,则答案等同于求另外一个数组的中位数 if(aEnd<=0) return B[bStart + kth -1]; //3. 递归到终点,两个数组的aStart和bStart已经到了中位数的位置 if(kth==1) return min(A[aStart],B[bStart]); int pa = min(kth/2,aEnd), pb = kth-pa; if(A[aStart + pa-1]< B[bStart +pb -1]) return find(A, aStart+pa, aEnd-pa, B, bStart, bEnd, kth-pa ); else return find(A, aStart, aEnd, B, bStart + pb, bEnd - pb,kth-pb); } public static int min(int a, int b) { return a>b?b:a; }}
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
- leetcode|4|Median of Two Sorted Arrays
- [Leetcode]4Median 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
- Leetcode[4] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- leetcode 4 -- Median of Two Sorted Arrays
- 编程练习题
- 静态块、动态块、构造函数、继承函数等的执行顺序
- php设置http请求头信息和响应头信息
- 提交项目到git远程仓库报错:error occurred during unpacking on the remote end: error Missing blob 261c12f4b8e2f5a
- 利用out关键字向函数传递List<T>参数遇到的问题
- LeetCode 4---Median of Two Sorted Arrays
- Python3 基础:返回函数和匿名函数
- Java基本数据类型
- curl如何发起DELETE/PUT请求
- 欢迎使用CSDN-markdown编辑器
- JS and Jquery 操作Form表单
- Linux下解决脚本错误
- cattle学航模之发动机篇
- C语言的Socket编程例子(TCP和UDP)