LeetCode-004-寻找两个正序数组的中位数
寻找两个正序数组的中位数
题目描述:给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:有序数组合并
将2个数组按顺序合并到一个大数组里面,2个数组都只会遍历一次。然后在大数组中获取中位数。
解法二:待完成
思考怎么在 时间复杂度为
O(log (m+n))下完成?
public class Solution {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] allNums = new int[nums1.length + nums2.length];
int i = 0, j = 0, x = 0;
int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;
for (; i < nums1.length || j < nums2.length; ) {
if (i < nums1.length) {
num1 = nums1[i];
}
if (j < nums2.length) {
num2 = nums2[j];
}
if (num1 < num2) {
allNums[x] = num1;
i++;
} else {
allNums[x] = num2;
j++;
}
x++;
num1 = Integer.MAX_VALUE;
num2 = Integer.MAX_VALUE;
}
int count = nums1.length + nums2.length;
if (count % 2 == 1) {
return allNums[count / 2];
} else {
return ((double) (allNums[count / 2 - 1] + allNums[count / 2])) / 2;
}
}
public static void main(String[] args) {
int[] nums1 = new int[]{1, 2};
int[] nums2 = new int[]{3, 4};
System.out.println(findMedianSortedArrays(nums1, nums2));
}
}
LeetCode-004-寻找两个正序数组的中位数的更多相关文章
- 微软面试题: LeetCode 4. 寻找两个正序数组的中位数 hard 出现次数:3
题目描述: 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2.请你找出并返回这两个正序数组的中位数. 进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决 ...
- [LeetCode]4.寻找两个正序数组的中位数(Java)
原题地址: median-of-two-sorted-arrays 题目描述: 示例 1: 输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并数组 = [1, ...
- leetcode-4. 寻找两个正序数组的中位数
leetcode-4. 寻找两个正序数组的中位数. 给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2. 请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(l ...
- leetcode 刷题(数组篇)4题 寻找两个正序数组的中位数(二分查找)
题目描述 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2.请你找出并返回这两个正序数组的 中位数 . 示例 1: 输入:nums1 = [1,3], nums2 = ...
- Leetcode随缘刷题之寻找两个正序数组的中位数
我一上来没读清题,想着这题这么简单,直接就上手写了: package leetcode.day_12_05; import java.util.ArrayList; import java.util. ...
- leetcode 4. Median of Two Sorted Arrays 寻找两个正序数组的中位数(困难)
一.题目大意 标签: 查找 https://leetcode.cn/problems/median-of-two-sorted-arrays 给定两个大小分别为 m 和 n 的正序(从小到大)数组 n ...
- 【LeetCode】4. Median of Two Sorted Arrays 寻找两个正序数组的中位数
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:数组,中位数,题解,leetcode, 力扣,python ...
- Leetcode4. 寻找两个正序数组的中位数
> 简洁易懂讲清原理,讲不清你来打我~ 输入两个递增数组,输出中位数和This的区别
感谢原文作者:王婷婷-Smily 原文链接:https://blog.csdn.net/dfshsdr/article/details/92760135 缘由 很多人认为多线程中的Thread.cur ...
- 超详细的node/v8/js垃圾回收机制
前言 垃圾回收器是一把十足的双刃剑.其好处是可以大幅简化程序的内存管理代码,因为内存管理无需程序员来操作,由此也减少了(但没有根除)长时间运转的程序的内存泄漏.对于某些程序员来说,它甚至能够提升代码的 ...
- 一键部署lamp 脚本
一键部署lamp 脚本 如下: #!/bin/bash systemctl stop firewalld systemctl disable firewalld setenforce 0 #----- ...
- MySQL语法命令之约束篇
文章目录 1.约束概述 1.1约束的分类 1.2添加约束 2.查看表中的约束 3. `not null` 非空约束 3.1 在 `create table` 时创建 3.2 在`alter table ...