LeetCode | Median of Two Sorted Arrays
来源:互联网 发布:超市扫码枪软件费用 编辑:程序博客网 时间:2024/05/17 16:42
题目
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)).
解答
解法一
比较容易想到的就是将这个两个数组合并,然后直接下标取值就可以了,合并时间为O(m+n),需要额外占用O(m+n)的空间。其实这个操作就是归并排序里面的最后一步了。本人拿到以后就准备采用这个方法,但明显时间复杂度打不到题目要求。
解法二
解法一再更进一步可以发现,其实我们只是要找到特定下标的数,而不需要排序结果,那么额外空间肯定是不需要的了,同样的方法可以找到目标值,时间复杂度和解法一相同。这个暂时算一个方法吧,比较直接,所有人都想得到。
解法三
这个方法是本人没有想到,将中位数转化为第k小数,其中k为(m + n)/ 2(根据偶数需要找两个),而找第k小数的算法,则充分利用类似二分法的策略,快速排除了很多不可能的区间,比较巧妙。
其实算法题要注意的就是问题的转化,已有算法思想的利用,看来本人还有待加强训练。
0 0
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - 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-004:Median of Two Sorted Arrays
- Leetcode 4 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
- 程序员面试宝典 7 - 指针与引用
- 学习Java的5个必经阶段
- Unity3D优化总结(一)
- leetcode 208 【trie】
- 字典的相关操作
- LeetCode | Median of Two Sorted Arrays
- 大端小端的证明
- POSIX 线程(一)
- 我们iTailor智能衣橱项目想法v1.0
- 第14周-输入输出流,文本文件-项目1 - 小玩文件(2)
- Leetcode Longest Common Prefix (java)
- leetcode - Count Complete Tree Nodes
- AspNet MVC4 教学-27:Asp.Net MVC4 自定义helper及function的快速Demo
- List,Map在遍历的时候remove