Searching for the median and finding k-elements in an ordered array

Source: Internet
Author: User

Problem Description:

Two sorted arrays A and B contain the number of M and N respectively, and find the median of two sorted arrays, requiring time complexity of O (log (m+n)). Converted to find two arrays of the K big number to solve

Problem solving Methods:

For a sorted column of length n, if n is an odd number, the median is A[N/2 + 1], if n is even, the median (a[n/2] + A[N/2 + 1])/2 If we can find the element K small in two series, we can solve the problem it may be possible to set the number of elements of a sequence of n, The number of B elements is m, each ascending order, the first k small element take a[k/2] b[k/2] compared, if a[k/2] > b[k/2] then, The element must not be in the first K/2 elements of B (proof of the Law) on the contrary, must not be in a of the former K/2 elements, So we can be a or B series of the former K/2 elements to delete, for the remaining two series of K-K/2 small elements, so that the size of the data is reduced to a similar problem, recursive resolution if the K/2 is greater than a number of numbers, the element must not be in the other sequence of the first K/2 elements, the same operation is Good.

Boundary conditions in the recursive process:

1. When one of the two arrays is empty, return the first k element of the other one directly

When will appear empty, when there is an array of valid comparison length is exactly k/2, and the element of this position is smaller than the element of another array, the array of effective comparison interval changes, this time will be an empty one is not empty, of course, can also be judged at the Beginning.

2, when k = = 1 o'clock, Returns the smaller value of the starting position of the two array

In addition, when recursively taking the K/2 element of each array, it is possible that the elements of a in the array are not enough, at this time the dik of the two elements must be in the position of the back k/2 of a and another array, at which point A's comparison element can be set to infinity, ensuring that the first K/2 elements of the other array are deleted

When one of the elements in an array is not enough k/2, set its length to L2, then L2 + L1 (in fact, K/2) < K must be set up, then for the above array to find the first K large can not be in front of the L1, must be in the two black parts, this time the above array of the former k/ 2 elements can be removed;

  

//As the question of finding the number of K in the two sequence, if it is an odd number, then it is the one that is found,//if it's an even number, look for K and k+1 Numbers.classSolution { public:    DoubleFindmediansortedarrays (vector<int>& nums1, vector<int>&Nums2) {        intTotallength = nums1.size () +nums2.size (); Doubleres; if(totallength &1) {res= Findkth (nums1,0, nums2,0, totallength/2+1); }Else{            DoubleTemp1 = findkth (nums1,0, nums2,0, totallength/2); DoubleTemp2 = findkth (nums1,0, nums2,0, totallength/2+1); Res= (temp1 + temp2)/2.0; }        returnres; }        DoubleFindkth (vector<int>& nums1,intstart1, vector<int>& nums2,intstart2,intIndex) {        if(start1 >=nums1.size ()) {            return(Double) Nums2[start2 + index-1]; }        if(start2 >=nums2.size ()) {            return(Double) Nums1[start1 + index-1]; }        if(index = =1){            returnmin (nums1[start1], nums2[start2]); }        intNums1_key = Start1 + index/2-1>= nums1.size ()? Int_max:nums1[start1 + index/2-1]; intNums2_key = Start2 + index/2-1>= nums2.size ()? Int_max:nums2[start2 + index/2-1]; if(nums1_key <Nums2_key) {            returnfindkth (nums1, Start1 + index/2, nums2, start2, index-index/2); }Else{            returnfindkth (nums1, start1, nums2, Start2 + index/2, index-index/2); }    }};
find Kth and find Midian

In addition to finding the K-large number of two arrays, in addition to the above method can be used, but also using the small top heap, with the result of heap data to achieve, such method is O (n) level, but for the data structure such as linked list does not provide random read-write can only use the small top heap method to Solve.

In addition to the O (n) calculation method, There is a more cumbersome method is to first merge the two targets together, and then directly to find it can be, for multiple arrays or multiple linked lists can do So.

2, looking for k-large elements

Problem Description: Find the element K in the array, This can be found using a quick selection, always time complexity is o (nlogn), similar to the fast row

Using the idea of the split, the middle position element is divided into the left and right parts, and then the main element K is judged to be the first and second side, and then to search recursively.

  

classSolution { public:    /** param k:description of k * param nums:description of array and index 0 ~ n-1 * return:description of return*/    intKthlargestelement (intk, vector<int>Nums) {        //Write your code here//Quickselect        if(nums.size () <k) {            return-1; }        returnKthhelper (nums,0, Nums.size ()-1, k); }        intKthhelper (vector<int>& nums,intStartintEndintk) {        if(start = =End) {            returnnums[start]; }                intleft =start; intright =end; intMid = start + (end-start)/2; intSign =nums[mid];  while(left <=right ) {             while(left <= right && nums[left] >sign ) { left++; }                         while(left <= Right && nums[right] <sign ) { right--; }            if(left <=right ) {                inttemp =nums[left]; nums[left]=nums[right]; nums[right]=temp; left++; right--; }        }                if(start + k-1<=right ) {            returnkthhelper (nums, start, right, k); }                if(start + k-1>=left ) {            returnKthhelper (nums, left, end, k-left +start); }                returnNums[right +1]; }};
Quick Pick

Searching for the median and finding k-elements in an ordered array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.