log(m+n)时间找到中位数
来源:互联网 发布:java web国际化 编辑:程序博客网 时间:2024/05/16 14:42
昨天晚上我的室友出了一道题目:
现在有两个已经有序的数组A和B,A有m个元素,B有n个元素。现在使用log(m+n)的复杂度计算出它们的中位数。我大致想了一下,用分治算法。然后今天写出了代码:
/*This file implements : For two ordered arrays A with m integers and B with n integers.please find the median number within log(m + n) time.*/#include <stdio.h>void find_median_number(int A[], int start_1, int B[], int start_2, int kth_smallest, int size_of_A, int size_of_B) {int temp;int end_1;int end_2;int compare_from_A;int compare_from_B;int bound = 0;while (1) {bound = 0;if (start_1 >= size_of_A) {start_1 = size_of_A - 1;}if (start_2 >= size_of_B) {start_2 = size_of_B - 1;}if (1 == kth_smallest) {temp = A[start_1] > B[start_2] ? B[start_2] : A[start_1];fprintf(stdout, " median : %d \n", temp);return;}end_1 = start_1 + (kth_smallest + 1) / 2 - 1;end_2 = start_2 + (kth_smallest + 1) / 2 - 1;if (end_1 >= size_of_A) {end_1 = size_of_A - 1;bound = 1;} if (end_2 >= size_of_B) {end_2 = size_of_B - 1;bound = 2;}compare_from_A = A[end_1];compare_from_B = B[end_2];if (compare_from_A > compare_from_B) {if (2 == bound) {/*stop*/temp = start_1 + kth_smallest - (end_2 - start_1 + 1) - 1; fprintf(stdout, "median : %d\n", A[temp]);return;}start_2 = end_2 + 1;} else {start_1 = end_1 + 1;if (1 == bound) {/*stop*/temp = start_2 + kth_smallest - (end_1 - start_1 + 1) - 1; fprintf(stdout, "median : %d\n", B[temp]);return;}}kth_smallest = (kth_smallest + 1) / 2;}//find_median_number(A, start_1, B, start_2, (kth_smallest + 1) / 2, size_of_A, size_of_B);}int main() {int a[] = {1, 2, 3, 4, 5 , 6, 7, 8, 9, 10};int b[] = {1, 2, 3 };int kth_smallest = (sizeof(a) / sizeof(int) + sizeof(b) / sizeof(int) + 1) / 2;find_median_number(a, 0, b, 0, kth_smallest, sizeof(a) / sizeof(int), sizeof(b) / sizeof(int));return 0;}一些细节的问题还是要考虑清楚的。
- log(m+n)时间找到中位数
- 求n^m 时间复杂度log(m)的算法
- LeetCode Median of Two Sorted Arrays 在两个已排列的数组中找出中位数。时间复杂度为O(log(min(N,M))
- Java实现O(log(n+m))两个有序数组中第K大元素或中位数
- leetcode:Median of Two Sorted Arrays (找两个序列的中位数,O(log (m+n))限制) 【面试算法】
- C实现 log n(m)
- 两个无序数组分别叫A和B,长度分别是m和n,求中位数,要求时间复杂度O(m+n),空间复杂度O(1) 。
- 求两个不等长、有序数组的中位数非常简洁的O(log(min(M,N)))迭代解详细解释
- 庞果英雄会-合法字符串 复杂度 O(log(n)*log(n)*log(m))
- O(n)时间求最接近中位数的k个数
- O(n)时间求最接近中位数的k个数
- 求一个数组的中位数时间复杂度为O(n)
- 找出n个数字的中位数至少需要的时间
- O(n)线性时间找第K大,中位数
- 关于中位数的时间复杂度为什么是O(n)
- bfprt算法,中位数的中位数算法,O(n)时间复杂度求解第k大数
- 找到N个无序数中第M大的数
- 报数出队,输入n与m,找到最后一个人
- Get machine IP and location via open api private static string GetOwnPublicIP() {
- 如何学好JAVA
- POJ 2704(Pascal's Travels-裸dp)
- (char) (Math.random() * 26 + 'A')
- 温故而知新:Delegate,Action,Func,匿名方法,匿名委托,事件
- log(m+n)时间找到中位数
- java web工程,过滤器判断session失效
- android进程讲解2
- Java 单例模式详解
- 【小蒙淘金】3.25晚评-黄金白银行情分析及部分操作建议
- Meta
- 图片阴影效果和影子效果
- 关于 windows 不能在本地计算机中启动tomcat服务问题的解决方案
- python动态导入模块、检查模块是否安装