LeetCode 之 Median of Two Sorted Arrays
来源:互联网 发布:plc和单片机有什么区别 编辑:程序博客网 时间:2024/06/03 17:44
题目链接:Median of Two Sorted Arrays
这道题目就是寻找两个排序后的数组的中位数,两个数组的长度分别为m和n,那么若m+n为偶数的话,则中位数为第(m+n)/2和第(m+n)/2+1个数,为奇数的话,就是第(m+n)/2+1个数。
这道题就可以考虑为如何寻找第K个数的问题。
设置指针i和j分别指向两个数组中的元素,依次遍历对比数值的大小,且设置k,寻找第第(m+n)/2和第(m+n)/2+1个数。
其中需要考虑到,当数组为空的情况,已经两个数组的长度均为1的情况。
代码如下:
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; //特殊情况 if(len1==0){ if(len2%2==0) return (double)(nums2[len2/2-1]+nums2[len2/2])/2; else return (double)nums2[len2/2]; } if(len2==0){ if(len1%2==0) return (double)(nums1[len1/2-1]+nums1[len1/2])/2; else return (double)nums1[len1/2]; } if(len1==1&&len2==1) return (double)(nums1[0]+nums2[0])/2; int i=0,j=0; int k=0; double tmp1 = 0,tmp2 = 0; while(i<len1&&j<len2){ k++; if(k==(len1+len2)/2) tmp1 = nums1[i]<nums2[j]?nums1[i]:nums2[j]; if(k==(len1+len2)/2+1){ tmp2 = nums1[i]<nums2[j]?nums1[i]:nums2[j]; break; } if(nums1[i]<nums2[j]) i++; else j++; } if(i>=len1){ if(k<(len1+len2)/2){ tmp1 = nums2[j+(len1+len2)/2-k-1]; } if(k<(len1+len2)/2+1){ tmp2 = nums2[j+(len1+len2)/2-k]; } } if(j>=len2){ if(k<(len1+len2)/2) tmp1 = nums1[i+(len1+len2)/2-k-1]; if(k<(len1+len2)/2+1) tmp2 = nums1[i+(len1+len2)/2-k]; } if((len1+len2)%2==0) return (tmp1+tmp2)/2; else return tmp2;}}
阅读全文
0 0
- leetcode之 median of two sorted arrays
- LeetCode之Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- LeetCode 之 Median of Two Sorted Arrays
- Leetcode之Median of Two Sorted Arrays
- leetcode之Median of Two Sorted Arrays
- leetcode之Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- leetcode 之 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- leetcode之 median of two sorted arrays
- LeetCode之Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- LeetCode之Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- leetcode之 median of two sorted arrays
- leetcode之 median of two sorted arrays
- leetcode之 median of two sorted arrays
- HDU 2062:Subset sequence
- fzu 2244 Daxia want to buy house
- linux(十)时间同步
- C语言------文件操作+字符串里的运算
- No rule to make target `include/config/auto.conf', needed by `include/ config/kernel.release'. stop
- LeetCode 之 Median of Two Sorted Arrays
- MP3播放
- C++——面向对象(二)——默认的构造函数(2)
- 通过伪类选择器调整链接属性
- Java多线程”JUC”集合中的CopyOnWriteArraySet
- 编译gnutls找不到nettle3.1的问题
- 实现基于Haproxy+Keepalived负载均衡高可用架构
- Linux——高性能服务器编程,多进程编程
- bootstrap之breadcrumb&panel样式