当前位置: 首页 > news >正文

【面试题】【C语言】寻找两个正序数组的中位数

寻找两个正序数组的中位数

仅供学习

题目

在这里插入图片描述


算法时间复杂度

二分查找算法,时间复杂度为 O(log(min(m, n))),其中 m 和 n 分别是两个数组的长度。

子函数

查找两个数字的最大值

int max(int a, int b) {return a > b ? a : b;
}

查找两个数字的最小值

int min(int a, int b) {return a < b ? a : b;
}

findMedianSortedArrays

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {// Ensure nums1 is the smaller arrayif (nums1Size > nums2Size) {return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size);}int x = nums1Size;int y = nums2Size;int low = 0;int high = x;while (low <= high) {int partitionX = (low + high) / 2;int partitionY = (x + y + 1) / 2 - partitionX;int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1];int minX = (partitionX == x) ? INT_MAX : nums1[partitionX];int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1];int minY = (partitionY == y) ? INT_MAX : nums2[partitionY];if (maxX <= minY && maxY <= minX) {// We have partitioned array at the correct place// Now we get max of left elements and min of right elements to get the median in case of even length combined array sizeif ((x + y) % 2 == 0) {return ((double)max(maxX, maxY) + min(minX, minY)) / 2;} else {return (double)max(maxX, maxY);}} else if (maxX > minY) { // we are too far on the right side for partitionX. Go on left side.high = partitionX - 1;} else { // we are too far on the left side for partitionX. Go on right side.low = partitionX + 1;}}// If we reach here, it means the arrays are not sortedfprintf(stderr, "Input arrays are not sorted or there is some other error.\n");return -1;
}

说明

  • 该代码实现了一个查找两个正序数组中位数的算法,使用了二分查找法来优化时间复杂度。
  • findMedianSortedArrays 函数首先确保第一个数组(nums1)是较小的一个,这样可以减小搜索范围。
  • 在 while 循环中,通过二分查找确定两个数组的分割点,使得分割后的左半部分和右半部分元素数量接近。
  • 根据分割点计算最大左边元素和最小右边元素,进而确定中位数。
  • 主函数通过示例数据验证了算法的正确性。
http://www.lryc.cn/news/413346.html

相关文章:

  • 原始的原型链是怎样玩的
  • RabbitMQ高级篇(如何保证消息的可靠性、如何确保业务的幂等性、延迟消息的概念、延迟消息的应用)
  • 正点原子imx6ull-mini-Linux驱动之platform设备驱动实验(14)
  • z3基础学习
  • 开发助手专业版,有反编译等多种功能
  • 嵌入式初学-C语言-十一
  • 浅谈几个常用OJ的注册方式
  • Html实现全国省市区三级联动
  • 前端构建工具Webpack 与 Vite 大对比
  • Ubuntu-22.04环境搭建
  • 嵌入式学习---DAY17:共用体与位运算
  • 蓝牙网关和蓝牙MESH总结
  • 了解关于标准化的知识
  • 【云原生】数据库忘记密码怎么办?
  • Postman 接口测试详解
  • 【JavaEE】线程状态
  • C++笔记之编译过程和面向对象
  • ModuleNotFoundError: No module named ‘tqdm‘
  • 东京电影节公布2024年竞赛片评审团成员并对其业绩分别进行评介 没什么含金量
  • 智能景区垃圾识别系统:基于YOLO的深度学习实现
  • ventoy和微pe可以共存吗?ventoy和pe共存使用教程
  • 如何获取和安装SSL证书
  • makefile在IC设计中的使用笔记
  • Suno声称在受版权保护的音乐上训练模型属于“合理使用“
  • Java | Leetcode Java题解之第316题去除重复字母
  • Taro学习记录
  • Spring Cache框架详解
  • 解决Html iframe 内嵌video标签导致视频无法全屏展示的问题
  • 谷粒商城实战笔记-110~114-全文检索-ElasticSearch-查询
  • 【开源】嵌入式Linux(IMX6U)应用层综合项目(1)--云平台调试APP