[leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
来源:互联网 发布:被淘宝大学骗了怎么办 编辑:程序博客网 时间:2024/05/18 03:56
先用图片讲下大概的原理:
下面是实现的代码:
代码基本上是按照leetcode中的某位大神的c++代码改写为java的
地址为:https://leetcode.com/discuss/30807/o-lg-m-n-c-solution-using-kth-smallest-number
public class MedianOfTwoSortedArrays{ public int kth(int a[],int sa,int lena, int b[],int sb,int lenb,int k){ if(lena < lenb) return kth(b,sb,lenb,a,sa,lena,k); //将较短的数组放置到后面 //上一行的代码的理由是,保证 int j = Math.min(lenb,k/2) 是对小数组进行处理 //如果比进行调换,int j = Math.min(lenb,k/2) 对大的数组进行处理,得出j=k/2 i=k/2 将可能造成数组的越界 if(lenb == 0) return a[sa+k-1]; //其中一个数组为0 那么k值必定在另一个数组中 if(k == 1) return Math.min(a[sa],b[sb]); //如果k=1,那么就其中的最小者 int j = Math.min(lenb,k/2);//保证不会越界 int i = k-j; if(a[sa+i-1]>b[sb+j-1]) return kth(a,sa,i,b,sb+j,lenb-j,k-j); else return kth(a,sa+i,lena-i,b,sb,j,k-i); } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int k = (len1+len2)/2; int result1 = kth(nums1,0,len1,nums2,0,len2,k+1); if((len1+len2)%2 == 0){ int result2 = kth(nums1,0,len1,nums2,0,len2,k); return((result1+result2)*1.0/2); //这里求的是两个数的均值 } return result1; }}
0 0
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- 【数组&中位数&第K位数】Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays,找出两个排好序的数组的中位数
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- leetcode Median of Two Sorted Arrays java 两个排序数组的中位数
- leetcode解题之4. Median of Two Sorted Arrays java (两个排序数组的中位数)
- 两个有序数组的中位数 Median of Two Sorted Arrays
- Median of Two Sorted Arrays 两个数组的中位数
- 【LeetCode-面试算法经典-Java实现】【004-Median of Two Sorted Arrays(两个排序数组的中位数)】
- 【数组】两个排序数组的中位数Median of Two Sorted Arrays
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- LeetCode | Median of Two Sorted Arrays(两个数组的中位数)
- LeetCode OJ 之 Median of Two Sorted Arrays(两个有序数组的中位数)
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- LeetCode 4. Median of Two Sorted Arrays(两个有序数组的中位数)
- [Leetcode #4]Median of Two Sorted Arrays 计算两个有序数组的中位数
- 4.leetcode Median of Two Sorted Arrays(medium)[求两个数组的中位数]
- Oracle常用sql总结
- 链表的java实现以及基本的增加,删除,排序操作
- STC89c51单片机的定时器2
- JDBC学习笔记
- MarkDown编辑器推荐
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- GPIO
- Spring MVC+Mybatis+Maven+Velocity+Mysql整合实例
- 分类的使用注意
- js页面跳转整理
- UIPickerView和UIDatePicker常用属性
- 用代码为视图添加约束, VFL语法总结, 网址:www.iphonetrain.com 公司:星宇无限(北京)科技有限公司
- 博客开启
- 添加一个c文件,编译报错