在 C++ 中查找一个连接 M 次的数组的第 k 个最小元素
假设我们有一个数组 A,以及其他两个整数 K 和 M。在将数组连接到自身 M 次后,我们必须找到 Kth 最小元素。假设数组像 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
Advertisement
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP