Problem description: there are now n ordered arrays in M groups, such as {1, 2, 3, 4}, {2, 3, 6}, {1, 3, 5, 7 }, select the data smaller than K in these arrays and return this value.
Idea: Compare the minimum data selected each time by referring to the process of merging two Arrays
1. Define the selection position array index [m], initialized to 0
2. Find the Rochelle row Array Based on Index [m] each time to make sure that the current position of the Rochelle row array at the current time is the minimum value. Make sure that the value of index [I] is less than N.
3. Retrieve the minimum value. The index [l_row] is auto-incremented by 1.
4. Search until the k is found.
1 public static int GetK_Min(int k) 2 { 3 int m=3,n=4; 4 if(k>m*n) 5 return -1; 6 int A[][] = {{1,3,5,6},{2,4,6,8},{1,2,4,6}}; 7 8 int index[] = {0,0,0}; 9 int l_min=0,l_row; 10 while(k>0)11 {12 for(int t=0;t<m;t++)13 {14 if(index[t]<n)15 {l_min = A[t][index[t]];break;}16 }17 18 l_min = 100;19 l_row = 0;20 for(int i=0;i<m;i++)21 {22 if(index[i]<n && l_min > A[i][index[i]])23 {24 l_min = A[i][index[i]];25 l_row = i;26 }27 }28 index[l_row] ++;29 30 k--;31 }32 33 return l_min;34 }
Algorithm analysis:
The time complexity of this algorithm is O (K * m), which is less complex than searching after merging and sorting.
There are now n ordered arrays in the M group, such as {1, 2, 3, 3}, {2, 3, 4, 6}, {1, 3, 5, 7}. In these arrays, select the data smaller than K, then return this value