LeetCode 算法第四题
来源:互联网 发布:淘宝怎样延长收货时间 编辑:程序博客网 时间:2024/06/12 00:00
Description
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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Code
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int n = (nums1Size >= nums2Size) ? nums1Size : nums2Size; int m = nums1Size + nums2Size - n; int *sn = (nums1Size >= nums2Size) ? nums1 : nums2; int *sm = (nums1Size < nums2Size) ? nums1 : nums2; int imin, imax, i, j, ihalf, max_left, min_right; imin = 0; imax = m; ihalf = (m + n + 1)/2; while(imin <= imax){ i=(imin + imax)/2; j=ihalf-i; if(i<m && sn[j-1]>sm[i]) imin = i+1; else if(i > 0 && sm[i-1]>sn[j]) imax = i-1; else{ if(i == 0) max_left = sn[j-1]; else if(j == 0) max_left = sm[i-1]; else max_left = (sn[j-1] > sm[i-1]) ? sn[j-1] : sm[i-1]; if((m+n)%2 == 1) return max_left; if(i == m) min_right = sn[j]; else if(j == n) min_right = sm[i]; else min_right = (sn[j] < sm[i]) ? sn[j] : sm[i]; return (min_right + max_left)/2.0; } } return 0;}
Reference
@MISSMARY的分析
Discussion
- Understand the definition and find out the essential need of the problem.
- pseudo-code
- special cases analysis
- coding
阅读全文
0 0
- LeetCode 算法第四题
- LeetCode 第四题
- leetcode 第四题
- 算法 上机 第四题
- LeetCode第四题,Add Two Numbers
- 每天一题LeetCode[第四天]
- 算法出的第四题的图
- 刷CCF算法题(第四天)
- Leetcode第四周周赛
- Leetcode sql算法题
- leetcode算法刷题
- LeetCode | HouseRobber 算法题
- leetcode算法第二题
- LeetCode算法题典
- leetcode算法刷题
- HappyNumber leetcode算法题
- Leetcode 算法题01
- Leetcode 算法题02
- /chroot环境搭建
- 位图和矢量图详解
- 页面屏蔽鼠标右键
- Java锁的种类及辨析(二):可重入锁
- 物流链云平台成品仓-wms简介
- LeetCode 算法第四题
- JavaFx在Mac OS中实现系统样式的菜单
- jQuery 语法
- Linux目录结构和常用命令
- PgRouting CentOs6 安装以及使用
- Linux下区分物理CPU、逻辑CPU和CPU核数
- *args和**kwargs
- webpack项目流程学习(二)
- 漏洞利用查询工具sandi