[LeetCode OJ][004]Median of Two Sorted Arrays
来源:互联网 发布:无线通信与网络 编辑:程序博客网 时间:2024/06/07 06:00
有长度分别为m和n的两个有序数组A和B。寻找这两个有序数组的中位数。整体的时间复杂度应当为O(log(m+n))。
我的想法:
- 有序数组应该是指升序
- O(log(m+n))应该和二分查找有关,但是我没有思路
- 假设两个数组已经合并,因为数组有序,所以中位数所在的位置是确定的
C89版(16ms):
double findMedianSortedArrays(int A[], int m, int B[], int n){ int i = 0, j = 0; int total = (m + n) >> 1; while(i + j < total && i < m && j < n) { if(A[i] > B[j]) { ++j; } else { ++i; } } if(i == m) { j = total - i; // aka total - m; if((m ^ n) & 0x00000001) { return B[j]; } else { return 1.0 * ((A[i-1] > B[j-1] ? A[i-1] : B[j-1]) + B[j]) / 2; } } else if(j == n) { i = total - j; // aka total - n; if((m ^ n) & 0x00000001) { return A[i]; } else { return 1.0 * ((A[i-1] > B[j-1] ? A[i-1] : B[j-1]) + A[i]) / 2; } } else { if((m ^ n) & 0x00000001) { return A[i] > B[j] ? B[j] : A[i]; } else { return 1.0 * ((A[i-1] > B[j-1] ? A[i-1] : B[j-1]) + (A[i] > B[j] ? B[j] : A[i])) / 2; } }}
0 0
- LeetCode OJ:Median of Two Sorted Arrays
- LeetCode OJ : Median of Two Sorted Arrays
- LeetCode OJ : Median of Two Sorted Arrays
- LeetCode OJ Median of Two Sorted Arrays
- [LeetCode OJ][004]Median of Two Sorted Arrays
- 【LeetCode OJ 004】Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- [LeetCode]-004-Median of Two Sorted Arrays
- 004 Median of Two Sorted Arrays [Leetcode]
- [LeetCode]004-Median of Two Sorted Arrays
- Leetcode 004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays *
- leetcode-004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays
- LeetCode-004 Median of Two Sorted Arrays
- leetcode 004 Median of Two Sorted Arrays
- LeetCode OJ - Median of Two Sorted Arrays (5*)
- LeetCode OJ 4 Median of Two Sorted Arrays
- 基于Cocos Studio 2.0获取某个节点的方法
- d叉堆 d-ary
- NOJ1042 区间最值 裸RMQ
- 【线性回归笔记】局部加权回归
- 优先队列的使用
- [LeetCode OJ][004]Median of Two Sorted Arrays
- 新手学C++ 运行代码时候闪退怎么办啊?
- LeetCode Divide Two Integers
- POJ 题目1318 Word Amalgamation(排序,水)
- soj1084滑雪比赛
- C语言游戏必备:光标定位与颜色设置的实现方法
- Code[VS] 1031 素数环
- C语言:函数二维数组传递方法
- java之数据溢出