考虑我们有一个数组A,还有另外两个整数K和M。将数组与自身连接M次后,必须找到第K个最小元素。假设数组像A = [3,1,2],K = 4且M = 3,所以在将A串联3次之后,它将是[3,1,2,3,1,2,3,1 ,2],则第4个最小元素为2。
为解决此问题,我们将对数组A进行排序,然后返回数组索引((K – 1)/ M)处的值。
#include<iostream> #include<algorithm> using namespace std; int findKSmallestNumber(int A[], int N, int M, int K) { sort(A, A + N); return (A[((K - 1) / M)]); } int main() { int A[] = { 3, 1, 2 }; int M = 3, K = 4; int N = sizeof(A) / sizeof(A[0]); cout << K << "th smallest number after concatenating " << M << " times, is: "<<findKSmallestNumber(A, N, M, K); }
输出结果
4th smallest number after concatenating 3 times, is: 2