LeetCode 4. 寻找两个有序数组的中位数
2023-09-11 14:21:10 时间
LeetCode 4. 寻找两个有序数组的中位数
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
知识点:
- sort(); // 升序排列
- array_merge(); // 数组合并
- 数 & 1 == 1 奇数,数 & 1 == 0 偶数
- >> 1, 整除 2
- sprinf('%.1f', 12.231); // 格式化返回数据
- round(12.213, 1); // 格式化返回数据
- printf('%.1f', 12.213); // 格式化输出
PHP代码:
function findMedianSortedArrays($nums1, $nums2) { $nums = array_merge($nums1, $nums2); sort($nums); $ans = count($nums) & 1 == 1 ? $nums[count($nums) - 1 >> 1] : ($nums[count($nums) >> 1] + $nums[(count($nums) >> 1) - 1]) / 2; return sprintf('%.1f', $ans); }
相关文章
- Leetcode: Paint House
- Leetcode: Reverse Nodes in k-Group
- 【LeetCode-面试算法经典-Java实现】【033-Search in Rotated Sorted Array(在旋转数组中搜索)】
- LeetCode高频题:最少经过几次操作可以使数组变为非降序状态
- LeetCode高频题:三个长度为N的无序数组A,B,C,求 A[i] + B[j] + C[k] = 64 的(i , j, k )的组合总数量
- JS Leetcode 530. 二叉搜索树的最小绝对差 题解分析,再次了解中序遍历
- [LeetCode]1431. 拥有最多糖果的孩子
- LeetCode 845. 数组中的最长山脉
- LeetCode数据结构_C语言题解系列-数组
- 116、【回溯算法】leetcode ——17. 电话号码的字母组合:回溯法:哈希映射+字符串数组映射(C++版本)
- 【leetcode】力扣 --- 日积月累,每日一题——3 寻找两个正序数组的中位数
- 【LeetCode】119. Pascal's Triangle II
- LeetCode 26. 删除排序数组中的重复项
- [LeetCode] 1253. Reconstruct a 2-Row Binary Matrix 重构 2 行二进制矩阵
- [LeetCode] 1207. Unique Number of Occurrences 独一无二的出现次数
- [LeetCode] 1031. Maximum Sum of Two Non-Overlapping Subarrays 两个不重叠的子数组的最大和
- [LeetCode] 1005. Maximize Sum Of Array After K Negations K次取反后最大化的数组和
- [LeetCode] 932. Beautiful Array 漂亮数组
- [LeetCode] Degree of an Array 数组的度
- [LeetCode] 215. Kth Largest Element in an Array 数组中第k大的数字
- leetcode 53. Maximum Subarray 最大子数组和(中等)