首页 > 其他分享 >【LeeCode】4. 寻找两个正序数组的中位数

【LeeCode】4. 寻找两个正序数组的中位数

时间:2022-12-17 21:31:47浏览次数:62  
标签:正序 num1 num2 int res sum LeeCode 中位数 length

【题目描述】

给定两个大小分别为 ​​m​​​ 和 ​​n​​​ 的正序(从小到大)数组 ​​nums1​​​ 和 ​​nums2​​。请你找出并返回这两个正序数组的 中位数 。

算法的时间复杂度应该为 ​​O(log (m+n))​​ 

​​​​​​​​​https://leetcode.cn/problems/median-of-two-sorted-arrays/description/​


【示例】

【LeeCode】4. 寻找两个正序数组的中位数_System

【代码】admin

import java.util.*;
// 2022-12-17

class Solution {

public double findMedianSortedArrays(int[] num1, int[] num2) {
double res = 0d;

// 考虑特殊情况
if (num1.length == 0 && num2.length == 0){
return res;
} else if (num1.length == 1 && num2.length == 0){
return num1[0];
} else if (num1.length == 0 && num2.length == 1) {
return num2[0];
}
// 因为本身数组都是正序的,这里进行合并
int[] sum = new int[num1.length + num2.length];
System.arraycopy(num1, 0, sum, 0, num1.length);
System.arraycopy(num2, 0, sum, num1.length, num2.length);
// 合并后的数组进行排序
Arrays.sort(sum);

if (sum.length % 2 == 0){
// 如果是偶数, 则mid取中间2数的均值
int left = sum.length / 2;
int right = sum.length / 2 + 1;
res = (double) (sum[left - 1] + sum[right - 1]) / 2;
}else {
// 如果是奇数, 取中间值
int mid = sum.length / 2 + 1;
res = sum[mid - 1];
}
// // System.out.println(res);
return res;
}
}

public class Main{
public static void main(String[] args) {
int[] arr = {3};
int[] arr1 = {-2, -1};
new Solution().findMedianSortedArrays(arr, arr1);
}
}




标签:正序,num1,num2,int,res,sum,LeeCode,中位数,length
From: https://blog.51cto.com/u_13682316/5950157

相关文章

  • 【LeeCode】17. 电话号码的字母组合
    【题目描述】给定一个仅包含数字 ​​2-9​​ 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。给出数字到字母的映射如下(与电话按键相同)。注意1不对......
  • 【LeeCode】53. 最大子数组和
    【题目描述】给你一个整数数组nums,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组是数组中的一个连续部分。​​​​https://leetcode.......
  • 【LeeCode】2488. 统计中位数为 K 的子数组 -- 太难了
    【题目描述】给你一个长度为n的数组nums,该数组由从1到n的不同整数组成。另给你一个正整数k。统计并返回num中的中位数等于k的非空子数组的数目。注意:数组......
  • 【LeeCode】栈和队列
    ​​学习参考​​【栈】importjava.util.*;//2022-12-15//栈:先进后出classMyStack{publicint[]elem;publicintuseSize;publicMyStack(){this......
  • [LeetCode]004-寻找两个正序数组的中位数
    >>>传送门题目给定两个大小分别为m和n的正序(从小到大)数组 nums1和 nums2。请你找出并返回这两个正序数组的中位数。算法的时间复杂度应该为O(log(m+n))。......
  • 【LeeCode】链表的学习
    基础知识​​学习参考​​importjava.util.*;//JAVA链表classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;......
  • 【LeeCode】1832. 判断句子是否为全字母句
    【题目描述】全字母句指包含英语字母表中每个字母至少一次的句子。给你一个仅由小写英文字母组成的字符串sentence,请你判断sentence是否为全字母句。如果是,返回true......
  • 【LeeCode】392. 判断子序列
    【题目描述】给定字符串 s 和 t ,判断 s 是否为 t 的子序列。字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例......
  • 剑指offer 数据流中的中位数(思维,堆)
    题目描述如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值......
  • 【LeeCode】剑指 Offer 42. 连续子数组的最大和
    【题目描述】输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)​​https://leetcode.cn/problems/lian-xu-zi-......