在不进行排序的情况下查找数组中n个最小值的索引
Find the index of the n-least values in a array without sorting
我有以下数组:
{7, 1, 3, 9, 5, 4, 7, 8, 2}
以及空的n尺寸阵列。现在,我想在不排序的情况下找到给定数组中n个最小值的索引,并将它们写入空数组。例如n=3:
{1, 8, 2}
有简单的方法吗?
如果不限制对其他数组进行排序,则创建一个索引数组,并根据原始数组对索引数组进行排序。
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
int main()
{
int n = 3;
// test data
std::vector<int> test = { 7, 1, 3, 9, 5, 4, 7, 8, 2 };
// index array
std::vector<int> index(test.size());
// set the index array to 0, 1, 2, … n-1
std::iota(index.begin(), index.end(), 0);
// sort the index array
std::sort(index.begin(), index.end(), [&](int n1, int n2) { return test[n1] < test[n2]; });
// output results -- note we are printing the index array
for (int i = 0; i < n; ++i)
std::cout << index[i] << "n";
}
输出:
1
8
2
从数组中的第一个值开始。
将数组中的值与n-least
数组中索引的值进行比较。(如果为空,则添加它(。
如果该值较小,则将数组从该位置偏移,并将索引添加到n-least
数组中的该位置。
如果不小于,则比较来自n-least
数组的下一个值,依此类推。
这可能不是最优的,但至少它不是一个简单的解决方案所能产生的O(n^2(复杂性。
我会用伪代码写这个:
n = 3
arr = [7, 1, 3, 9, 5, 4, 7, 8, 2]
narr = []
for i as 0 to sizeof(arr) - 1
for j as 0 to n - 1
if narr[j] is undefined or arr[i] < arr[narr[j]]
narr.shiftRight(j, 1)
narr[j] = i;
break
endif
endfor
endfor
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- txt 文件中浮点数的最大和最小值
- 余数运算符的等效操作,用于处理低于允许的最小值
- 需要使用模板查找数组的第二个最小和最小值
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 查找包含 N 个元素的数组的最小值和最大值
- 在不进行排序的情况下查找数组中n个最小值的索引
- 在索引0为0的数组中查找非零最小值C++
- 包含全局最小值的向量索引
- 使用函数从数组中索引最小值的问题
- C++:仅在具有指定索引的元素中查找数组中的最小值
- 在 for 循环中查找最小值并保留其索引
- 矢量中最大值和最小值的索引