Leet Code 4 Median of Two Sorted Arrays

2024-06-15 08:58
文章标签 code sorted two median arrays leet

本文主要是介绍Leet Code 4 Median of Two Sorted Arrays,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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)).


【算法思路】

       搜了一下leetcode的难度分布表(leetcode难度及面试频率)才发现,该问题是难度为5的问题,真是小看了它!网上搜了很多答案,但是鲜见简明正确的解答,唯有一种寻找第k小值的方法非常好,在此整理一下。

       首先对leetcode的编译运行吐槽一下:貌似没有超时判断,而且small和large的数据集相差很小。

1. 利用排序将两个数组合并成一个数组,然后返回中位数:

[cpp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. class Solution {  
  2. public:  
  3.     double findMedianSortedArrays(int A[], int m, int B[], int n) {  
  4.         // Start typing your C/C++ solution below  
  5.         // DO NOT write int main() function  
  6.         int *a=new int[m+n];  
  7.           
  8.         memcpy(a,A,sizeof(int)*m);  
  9.         memcpy(a+m,B,sizeof(int)*n);  
  10.           
  11.         sort(a,a+n+m);  
  12.           
  13.         double median=(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0);  
  14.           
  15.         delete a;  
  16.           
  17.         return median;  
  18.     }  
  19. };  

该方法居然也通过测试,但是其复杂度最坏情况为O(nlogn),这说明leetcode只对算法的正确性有要求,时间要求其实不严格。


2. 利用类似merge的操作找到中位数,利用两个分别指向A和B数组头的指针去遍历数组,然后统计元素个数,直到找到中位数,此时算法复杂度为O(n)。


3. 从medianof two sorted arrays中看到了一种非常好的方法。该方法的核心是将原问题转变成一个寻找第k小数的问题(假设两个原序列升序排列),这样中位数实际上是第(m+n)/2小的数。所以只要解决了第k小数的问题,原问题也得以解决。

首先假设数组A和B的元素个数都大于k/2,我们比较A[k/2-1]和B[k/2-1]两个元素,这两个元素分别表示A的第k/2小的元素和B的第k/2小的元素。

这两个元素比较共有三种情况:>、<和=。如果A[k/2-1]<B[k/2-1],这表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中。换句话说,A[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。

证明也很简单,可以采用反证法。假设A[k/2-1]大于合并之后的第k小值,我们不妨假定其为第(k+1)小值。

由于A[k/2-1]小于B[k/2-1],所以B[k/2-1]至少是第(k+2)小值。但实际上,在A中至多存在k/2-1个元素小于A[k/2-1],B中也至多存在k/2-1个元素小于A[k/2-1],所以小于A[k/2-1]的元素个数至多有k/2+ k/2-2,小于k,这与A[k/2-1]是第(k+1)的数矛盾。

当A[k/2-1]>B[k/2-1]时存在类似的结论。

当A[k/2-1]=B[k/2-1]时,我们已经找到了第k小的数,也即这个相等的元素,我们将其记为m。由于在A和B中分别有k/2-1个元素小于m,所以m即是第k小的数。(这里可能有人会有疑问,如果k为奇数,则m不是中位数。这里是进行了理想化考虑,在实际代码中略有不同,是先求k/2,然后利用k-k/2获得另一个数。)


通过上面的分析,我们即可以采用递归的方式实现寻找第k小的数。此外我们还需要考虑几个边界条件:

  • 如果A或者B为空,则直接返回B[k-1]或者A[k-1];
  • 如果k为1,我们只需要返回A[0]和B[0]中的较小值;
  • 如果A[k/2-1]=B[k/2-1],返回其中一个;

【CODE】

[cpp]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. double findKth(int a[], int m, int b[], int n, int k)  
  2. {  
  3.     //always assume that m is equal or smaller than n  
  4.     if (m > n)  
  5.         return findKth(b, n, a, m, k);  
  6.     if (m == 0)  
  7.         return b[k - 1];  
  8.     if (k == 1)  
  9.         return min(a[0], b[0]);  
  10.     //divide k into two parts  
  11.     int pa = min(k / 2, m), pb = k - pa;  
  12.     if (a[pa - 1] < b[pb - 1])  
  13.         return findKth(a + pa, m - pa, b, n, k - pa);  
  14.     else if (a[pa - 1] > b[pb - 1])  
  15.         return findKth(a, m, b + pb, n - pb, k - pb);  
  16.     else  
  17.         return a[pa - 1];  
  18. }  
  19.   
  20. class Solution  
  21. {  
  22. public:  
  23.     double findMedianSortedArrays(int A[], int m, int B[], int n)  
  24.     {  
  25.         int total = m + n;  
  26.         if (total & 0x1)  
  27.             return findKth(A, m, B, n, total / 2 + 1);  
  28.         else  
  29.             return (findKth(A, m, B, n, total / 2)  
  30.                     + findKth(A, m, B, n, total / 2 + 1)) / 2;  
  31.     }  
  32. };  


代码非常简洁,而且效率也很高。在最好情况下,每次都有k一半的元素被删除,所以算法复杂度为logk,由于求中位数时k为(m+n)/2,所以算法时间复杂度为log(m+n)。


【java 版】

暴力排序的复杂度O(n*log n)

 public static double findMedianLow(int A[], int B[]) {int[] sumArray = ArrayUtils.addAll(A, B);Arrays.sort(sumArray);int length = sumArray.length;if (length % 2 == 0) {double num1 = sumArray[length / 2];double num2 = sumArray[length / 2 - 1];return (num1 + num2) / 2;} else {return sumArray[length / 2];}}



public class Solution {public double findMedianSortedArrays(int A[], int B[]) {int m = A.length;int n = B.length;int total = m + n;//长度为积数取中间,为偶数去中间两个的平均值if ((total & 0x01) != 0) {return findKth(A, m, B, n, total / 2 + 1);} else {return (findKth(A, m, B, n, total / 2) + findKth(A, m, B, n,total / 2 + 1)) / 2.0;}}//二分法,每次都能去除掉一部分范围外数据。需要注意每次去除数据都会改变数组的结构,所以需要特殊处理临界值private static double findKth(int a[], int m, int b[], int n, int k) {if (m > n)  return findKth(b, n, a, m, k);  if (m == 0)  return b[k - 1];  if (k == 1)  return Math.min(a[0], b[0]);  //divide k into two parts  int pa = Math.min(k / 2, m), pb = k - pa;  if (a[pa - 1] < b[pb - 1])  return findKth(Arrays.copyOfRange(a, pa, m), m - pa, b, n, k - pa);  else if (a[pa - 1] > b[pb - 1])  return findKth(a, m, Arrays.copyOfRange(b, pb, n), n - pb, k - pb);  else  return a[pa - 1];  }
}


这篇关于Leet Code 4 Median of Two Sorted Arrays的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1062997

相关文章

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

Debugging Lua Project created in Cocos Code IDE creates “Waiting for debugger to connect” in Win-7

转自 I Installed Cocos Code IDE and created a new Lua Project. When Debugging the Project(F11) the game window pops up and gives me the message waiting for debugger to connect and then freezes. Also a

LLVM入门2:如何基于自己的代码生成IR-LLVM IR code generation实例介绍

概述 本节将通过一个简单的例子来介绍如何生成llvm IR,以Kaleidoscope IR中的例子为例,我们基于LLVM接口构建一个简单的编译器,实现简单的语句解析并转化为LLVM IR,生成对应的LLVM IR部分,代码如下,文件名为toy.cpp,先给出代码,后面会详细介绍每一步分代码: #include "llvm/ADT/APFloat.h"#include "llvm/ADT/S

VS Code 调试go程序的相关配置说明

用 VS code 调试Go程序需要在.vscode/launch.json文件中增加如下配置:  // launch.json{// Use IntelliSense to learn about possible attributes.// Hover to view descriptions of existing attributes.// For more information,

code: 400, msg: Required request body is missing 错误解决

引起这个错误的原因是,请求参数按照get方式给。 应该给json字符串才对 补充: 1. @RequestBody String resource 加@RequestBody必须给json字符串,否则会报错400,记如标题错误。 不加这个的进行请求的话,其实post和get就没有什么区别了。 2. List<String> indexCodes=(List<String>)json.

iOS项目发布提交出现invalid code signing entitlements错误。

1、进入开发者账号,选择App IDs,找到自己项目对应的AppId,点击进去编辑, 2、看下错误提示出现  --Specifically, value "CVYZ6723728.*" for key "com.apple.developer.ubiquity-container-identifiers" in XX is not supported.-- 这样的错误提示 将ubiquity

解决服务器VS Code中Jupyter突然崩溃的问题

问题 本来在服务器Anaconda的Python环境里装其他的包,装完了想在Jupyter里写代码验证一下有没有装好,一运行发现Jupyter崩溃了!?报错如下所示 Failed to start the Kernel. ImportError: /home/hujh/anaconda3/envs/mia/lib/python3.12/lib-dynload/_sqlite3.cpython-

Java多线程编程模式实战指南:Two-phase Termination模式

文章来源: http://www.infoq.com/cn/articles/java-multithreaded-programming-mode-two-phase-termination?utm_source=infoq&utm_campaign=user_page&utm_medium=link 文章代码地址: https://github.com/Visce

Behind the Code:与 Rakic 和 Todorovic 对话 OriginTrail 如何实现 AI 去中心化

原文:https://www.youtube.com/watch?v=ZMuLyLCtE3s&list=PLtyd7v_I7PGnko80O0LCwQQsvhwAMu9cv&index=12 作者:The Kusamarian 编译:OneBlock+ 随着人工智能技术的飞速发展,一系列前所未有的挑战随之而来:模型的衰退与互联网的潜在威胁愈发明显。AI 的增长曲线可能因训练过程中的瓶颈而趋于平

冒泡排序和鸡尾酒排序(code)

昨天回顾了下冒泡排序和鸡尾酒排序,用面向对象的方式写了一下,并且优化了代码,记录一下~ 一、冒泡排序 # 冒泡排序class BubbleSort(object):def __init__(self, data_list):self.data_list = data_listself.length = len(data_list)# 简单粗暴的排序方式def b_sort(self):d