Median of Two Sorted Arrays
来源:互联网 发布:手机淘宝无法安装 编辑:程序博客网 时间:2024/06/06 04:01
这道题标注是困难,就体验来说并没有单链表和求字符串那道题困难,不知道是我解题思路有问题还是没理解题意。
我读题目觉得大概是这个意思,出值永远是个数不大于2的短数组,每次两个,求两个数组的中值,
87ms,很慢的一个速度,再之前的版本中num1和2的长度没有存储导致时间被拖延到95ms,可见影响其实挺大的。
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length1 = nums1.length;
int length2 = nums2.length;
int[] array = new int[length1+length2];
for(int i=0;i < length1;i++){
array[i] = nums1[i];
}
for(int j=0;j < length2;j++){
array[j+length1] = nums2[j];
}
Arrays.sort(array);
int sum;
if(array.length%2 == 0){
int aa = (array.length-1)/2;
sum = array[aa]+array[aa+1];
return sum/2.0;
}else{
int aa = (array.length-1)/2;
sum = array[aa];
return sum;
}
}
然后百度一下发现我的想法可能确实不对,人家的意思是说从已经排好序的数组中找出中值来。然后按照我之前的思路,当数组很大的时候就当掉了。
84ms
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int total = len1 + len2;
if(total % 2==0){
return (findKth(nums1,nums2,total/2)+findKth(nums1,nums2,total/2+1))/2.0;
} else {
return findKth(nums1,nums2,total/2+1);
}
}
private int findKth(int[] nums1, int[] nums2, int k){ int p = 0, q = 0; for(int i = 0; i < k - 1; i++){ if(p>=nums1.length && q<nums2.length){ q++; } else if(q>=nums2.length && p<nums1.length){ p++; } else if(nums1[p]>nums2[q]){ q++; } else { p++; } } if(p>=nums1.length) { return nums2[q]; } else if(q>=nums2.length) { return nums1[p]; } else { return Math.min(nums1[p],nums2[q]); }}
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Maven的使用(Myeclipse)
- 通过递增快照备份 Azure 非托管 VM 磁盘
- Java集合总结之Collection整体框架
- Tomcat 架构分析(一) 体系结构
- onnx on OSX
- Median of Two Sorted Arrays
- Linux的内核相关问题
- Leetcode个人题解14
- ECMA-262-5 词法环境:通用理论(三)--- 标识符绑定
- [BZOJ]3110: [Zjoi2013]K大数查询 整体二分+线段树
- 【SpringBoot】SpringBoot更改项目编码集
- 设置图表数据标签:汪琪玩Excel第二十三招
- 2017年12月5日 17:14:03
- 批处理