The question is not difficult. The key is to clarify the boundary conditions. First, write a solution with the time complexity of O (k.
#include <iostream>using namespace std;//a[] increase//b[] decrease//use ret_value to return the result//function ret reprsent the error if not 0int find_k(int a[], int b[], int m, int n, int k, int& ret_value) { if(k<=0 || m<0 || n<0 || k>(m+n)) { return -1; } int i = 0, x = m-1, y = 0; while (i<k && x>=0 && y<=n-1) { if (a[x] > b[y]) { ret_value = a[x]; i++; x--; } else if (a[x] < b[y]) { ret_value = b[y]; i++; y++; } else { //equal ret_value = a[x]; i+=2; x--; y++; } } cout << "x:" << x << endl << "y:" << y << endl << "i:" << i << endl << "v:" << ret_value << endl; i = k-i; if (i > 0) { if (x<0) { ret_value = a[y+i-1]; } else if (y > n-1) { ret_value = a[x-i+1]; } } return 0;}int main () { int a[] = {1,2,3}; int b[] = {6,5,3}; int k=0; cout << "please input the k:"; cin >> k; int value = -1; find_k(a,b,3,3,k,value); cout << value << endl; return 0;}
Attach an algorithm implementation with the complex time server O (log n,
The algorithm IDEA is:
Each time we compare the number of K/2 in two arrays, and the number of K/2 in the array where the larger number is located, it must be in the top K number;
In this way, the number k/2 is excluded, and then the number k/2 is found in the remaining number, until the last number is found.
To simplify the process, we assume that both arrays are in descending order.
Note the 31 ~ 34 rows. If they are not judged to be equal, when there is one remaining number, 20th rows
mid_b = pb + kb -1;
Mid_ B will be assigned a wrong position, leading to an endless loop of programs.
//both a[] b[] decreaseint find_k_both_increase_O_log_k(int a[], int b[], int m, int n, int k, int& ret_value) { if(k<=0 || m<0 || n<0 || k>(m+n)) { return -1; } int ka = 0; int kb = 0; int pa = 0; int pb = 0; int mid_a = 0; int mid_b = 0; int i = k; while (i>0 && pa<m && pb<n) { ka = i/2; kb = i-ka; mid_a = pa + ka -1; mid_b = pb + kb -1; if (mid_a<m && mid_b<n) { if (a[mid_a] > b[mid_b]) { ret_value = a[mid_a]; pa = mid_a + 1; i = i - ka; } else if (a[mid_a] < b[mid_b]) { ret_value = b[mid_b]; pb = mid_b + 1; i = i - kb; } else { //equal ret_value = a[mid_a]; return 0; } } cout << "pa:" << pa << endl << "pb:" << pb << endl << "i:" << i << endl; cout <<endl; } if (i > 0) { if (pa > m-1) { ret_value = a[pb-1+i]; } else if (pb > n-1) { ret_value = a[pa-1+i]; } } return 0;}
This article is from the "new home of Tianyan prodigy" blog. For more information, contact the author!
Search for the k-th largest number in two sorted order arrays (one increasing and one decreasing)