问题:  查找出一给定数组中第k大的数.例如[3,2,7,1,8,9,6,5,4],第1大的数是9,第2大的数是8-- 思考:1. 直接从大到小排序,排好序后,第k大的数就是arr[k-1]. 2. 只需找到第k大的数,不必把所有的数排好序.我们借助快速排序中partition过程,一般情况下,在把所有数都排好序前,就可以找到第k大的数.我们依据的逻辑是,经过一次partition后,数组被pivot分成左右两部分:S左.S右.当S左的元素个数|S左|等于k-1时,pivot即是所找的数:当|S…
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)). t int MAX = 0x7fffffff, MIN = 0x80000000; int kth(vector<int>& nums1, vec…
貌似是去年阿里巴巴c++的笔试题,没有什么创新直接照搬的... 题意就是找出两个排序数组的中间数,其实就是找出两个排序数组的第k个数. 二分答案,先二分出一个数,再用二分算出这个数在两个排序数组排序第几,然后和k做比较,最后以这个比较为依据接着二分直到求出第k个数. 本来这是两重二分,由于楼主的懒已经没有办法治疗了,用库函数upper_bound()代替了第二重二分,有志者可以自己写第二重二分,楼主就偷懒了... 警告:由于题目很神奇,会出现两个排序数组为空的情况,楼主差点因为这个报警....…
二分.情况讨论 因为数组有序,所以能够考虑用二分.通过二分剔除掉肯定不是第k位数的区间.如果数组A和B当前处理的下标各自是mid1和mid2.则 1.假设A[mid1]<B[mid2], ①.若mid1+mid2+2==k(+2是由于下标是从0開始的),则 mid1在大有序数组中下标肯定小于k,所以能够排除[0,mid1].此外.B[mid2]下标大于或等于k.能够排除[mid2+1,n]: ②.若mid1+mid2+2<k,则 mid1在大有序数组中下标肯定小于k,所以能够排除[0,mid1…
思路: 利用快速排序的划分思想 可以找出前k大数,然后不断划分 直到找到第K大元素 代码: #include <iostream> #include <algorithm> #include <cstdio> using namespace std; int findK(int left, int right, int arr[], int k) { if(left >= right) return arr[left]; int first = left, las…
一道非常经典的题目,Median of Two Sorted Arrays.(PS:leetcode 我已经做了 190 道,欢迎围观全部题解 https://github.com/hanzichi/leetcode) 题意非常简单,给定两个有序的数组,求中位数,难度系数给的是 Hard,希望的复杂度是 log 级别.回顾下中位数,对于一个有序数组,如果数组长度是奇数,那么中位数就是中间那个值,如果长度是偶数,就是中间两个数的平均数. O(nlogn) 最容易想到的解法是 O(nlogn) 的解…
要求:Median of Two Sorted Arrays (求两个排序数组的中位数) 分析:1. 两个数组含有的数字总数为偶数或奇数两种情况.2. 有数组可能为空. 解决方法: 1.排序法 时间复杂度O(m+n),空间复杂度 O(m+n) 归并排序到一个新的数组,求出中位数. 代码: class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int *C = new int…
Median of Two Sorted Arrays There are two sorted arrays A and B 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)). time=378ms accepted <pre name="code" class="j…
LeetCode(3) || Median of Two Sorted Arrays 题记 之前做了3题,感觉难度一般,没想到突然来了这道比较难的,星期六花了一天的时间才做完,可见以前基础太差了. 题目内容 There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should…
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)). You may assume nums1 and nums2 cannot be both empty. Example 1:       nums1 =…