[leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
2015-08-13 21:02
615 查看
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)).
题目大意:略。中位数:即两个数组中下标为中间的一个。(一开始理解为找数的大小位于中间的一个,晕)
//判断数组是升序还是降序
size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
题目大意:略。中位数:即两个数组中下标为中间的一个。(一开始理解为找数的大小位于中间的一个,晕)
//判断数组是升序还是降序
int sort_direction(int* nums1, int nums1Size, int* nums2, int nums2Size) { if(nums1Size < 2) { if(nums2Size < 2) { return 0; } else { return (nums2[0] - nums2[nums2Size-1]); } } else { if(nums2Size < 2) { return (nums1[0] - nums1[nums1Size-1]); } else { if(nums1[0] != nums1[nums1Size-1]) return (nums1[0] - nums1[nums1Size-1]); else return (nums2[0] - nums2[nums2Size-1]); } } } double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int *merge = malloc(sizeof(int)*(nums1Size+nums2Size)); int *nums11 = malloc(sizeof(int)*(nums1Size+1)); int *nums22 = malloc(sizeof(int)*(nums2Size+1)); int *p = merge, *n1 = nums11, *n2 = nums22; int i = 0; int drt = sort_direction(nums1,nums1Size,nums2,nums2Size); int tmp; int len = 0; memcpy(nums11, nums1, sizeof(int)*(nums1Size+1)); memcpy(nums22, nums2, sizeof(int)*(nums2Size+1)); nums11[nums1Size] = (unsigned int)(-1) >> 1;<span style="white-space:pre"> </span>//边界哨兵值 nums22[nums2Size] = (unsigned int)(-1) >> 1; //printf("drt:%d\n", drt); memset(merge, 0x0, sizeof(int)*(nums1Size+nums2Size)); for(i = 0; i < nums1Size+nums2Size; i++) { { tmp = *nums11 < *nums22 ? *nums11++ : *nums22++; *merge++ = tmp; len++; } } /* printf("len:%d\n", len); for(i = 0; i < nums1Size+nums2Size; i++) { printf("%d ", p[i]); } printf("\n");*/ return (len%2 ? p[len/2] : (double)(p[len/2-1] + p[len/2])/2); }运行时间:24ms ,还可以优化,其他人的最快20ms
相关文章推荐
- Linux C函数参考手册(PDF版)
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua教程(十七):C API简介
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现打造气泡屏幕保护效果
- C#实现的算24点游戏算法实例分析
- C/C++数据对齐详细解析
- 利用C语言来求最大连续子序列乘积的方法
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 字符串的组合算法问题的C语言实现攻略
- C 语言基础教程(我的C之旅开始了)[三]
- 算法之排列算法与组合算法详解