题目链接: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)).

解题思路:将两个有序数组合并为一个,设置一个 Map<Integer, Integer>,key值为序号,value值为数值,m+n个数的中位数要分两种情况讨论:

1、m+n为奇数:则(m+n)/2即为其中位数

2、m+n为偶数:则(((m+n)/2-1)+(m+n)/2)/2为中位数

示例代码如下:

public class Solution
{
public static double findMedianSortedArrays(int[] nums1, int[] nums2)
{
int m=nums1.length;
int n=nums2.length;
int index; //中位数的位置
//m+n为奇数
double result;
if(m==1&&n==0)
return nums1[0];
if(m==0&&n==1)
return nums2[0];
Map<Integer, Integer> map=new TreeMap<Integer, Integer>();
int i=0,j=0,k=0;
while(i<m&&j<n)
{
if(nums1[i]<=nums2[j])
{
map.put(k,nums1[i]);
i++;
k++;
}
else
{
map.put(k,nums2[j]);
j++;
k++;
}
}
while(i<m)
{
map.put(k,nums1[i]);
i++;
k++;
}
while(j<n)
{
map.put(k,nums2[j]);
k++;
j++;
}
//m+n为奇数
if((m+n)%2==1)
{
result=map.get((m+n)/2);
return result;
}
else
{
result=(double)(map.get((m+n)/2-1)+map.get((m+n)/2))/2;
return result;
}
} }

最新文章

  1. windows 安装 mongodb
  2. Myeclipse8.6配置android_SDK,进行android开发(转载)
  3. submit 后台运行代码
  4. 基于HTML5的燃气3D培训仿真系统
  5. 黄金点游戏之客户端(homework-05)
  6. 8款JS框架比较
  7. POJ 3311 Hie with the Pie (BFS+最短路+状态压缩)
  8. js操作select和option
  9. iOS 创建OpenGL 环境的思考
  10. &lt;Mastering KVM Virtualization&gt;:第一章 了解Linux虚拟化
  11. 关于atom
  12. 6.19 noip模拟题(题目及解析转自 hzwer 2014-3-15 NOIP模拟赛)
  13. [luaj]在安卓用使用luaj
  14. Elasticsearch索引别名、Filtered索引别名、Template
  15. 《剑指offer》第六十一题(扑克牌的顺子)
  16. centos7-使用nginx做ftp站
  17. poj 3468 线段树 成段增减 区间求和
  18. windows开通https服务
  19. 深入浅出 kvm qemu libvirt
  20. python Django编写登录项目

热门文章

  1. Linux高级字符设备驱动 poll方法(select多路监控原理与实现)
  2. js 获取单选框和复选框的值和js dom方法给单选框和多选框赋值
  3. 【WPF】WPF DataGrid List数据源 双向绑定通知机制之ObservableCollection使用以及MultiBinding 的应用
  4. 嵌入式开发值zynq---zynq中tlv320aic23b spi的驱动移植
  5. CI框架 -- 核心文件 之 Lang.php(加载语言包)
  6. Java虚拟机垃圾收集器与内存分配策略
  7. 【FastJSON】使用JSON.toJSONString()-解决FastJson中“$ref 循环引用”的问题
  8. 生成asm-offset
  9. Java并发包学习一 ThreadFactory介绍
  10. RancherOS(ROS)如何安装到硬盘? 并设置为用户自动登录到系统? -a rancher.autologin=tty1