寻找最小的下一个更大的元素 [英] Finding smallest next bigger element
问题描述
我有一项任务,要求我为所有数组条目找到数组中所有较大元素中的最小元素,并将相应的索引存储在数组中,而我还不太清楚解决方案的最后一部分。
I have a task which requires me to find the smallest of all bigger elements in an array for all array entries and store the respective indexes in an array and I can't quite figure out the last part of the solution.
这有点类似于此处解释的问题:
https://www.geeksforgeeks.org/smallest-greater-elements-in-whole-array/
This is kind of similar to the problem explained here: https://www.geeksforgeeks.org/smallest-greater-elements-in-whole-array/
唯一的区别是仅考虑数组项右边的值(j> i),例如:
The only difference is that only the values right of the array entry are accounted for (j>i), e.g.:
input: [80; 19; 49; 45; 65; 71; 76; 28; 68; 66]
output: [-1; 7; 4; 4; 9; 6; -1; 9; -1; -1]
带有自平衡树的解决方案对我来说很有意义。但是,我仍然需要考虑索引,因为只有数组条目的解决方案权才有效。
The solution with a self balancing tree makes sense to me. However, I still need to account for the indexing because only the solutions right of the array entry are valid.
是否有一种方法可以将插入值的索引映射到树条目还是要创建具有相同结构的第二棵树,但是要使用旧数组条目的索引而不是作为节点的实际值?我不确定,因为自平衡树的结构当然取决于所插入的值(较大的值在右子树中,较小的值在左子树中)。
Is there a way to map the indexing of the inserted values to the tree entries or to create a second tree with an identical structure but the index of the old array entries instead of the actual values as nodes? I am not sure because the structure of the self-balancing tree of course depends on the values inserted (bigger values right subtree, smaller values left subtree).
编辑:实际上第二个AVL树可能无济于事,因为我必须检查遍历树时索引的大小是否更大以及数组项是否更大...
Actually a second AVL tree propably won't help as I have to check that indexing is bigger AND array entry is bigger while traversing the tree...
推荐答案
最简单的解决方案是从右到左遍历输入,对于每个元素,查找树中第一个更大的元素(或具有O(LogN)查找和插入的任何数据结构),然后将该元素添加到树中。这样,更大的元素将始终位于输入中的元素之后。
The simplest solution is to iterate over the input from right to left, and for each element look up the first greater element in a tree (or any data structure with O(LogN) look-up and insertion), and then add the element to the tree. That way the greater element always comes after the element in the input.
对于C ++版本,可以使用 std :: map
,其中元素的值是键,而元素在输入中的索引为值,并使用 upper_bound
获取下一个更大的值:
For a C++ version, you can use a std::map
where the element's value is the key and the element's index in the input is the value, and use upper_bound
to get the next greater value:
#include <iostream>
#include <vector>
#include <map>
void nextValues(std::vector<int> &in, std::vector<int> &out) {
std::map<int, int> tree;
for (int i = in.size() - 1; i >= 0; i--) {
out.insert(out.begin(), tree.upper_bound(in[i])->second - 1);
tree.insert(std::pair<int, int>(in[i], i + 1));
}
}
int main() {
std::vector<int> a = {80,19,49,45,65,71,76,28,68,66};
std::vector<int> b;
nextValues(a, b);
for (int i : b) std::cout << (int) i << ","; // -1,7,4,4,9,6,-1,9,-1,-1
return 0;
}
这篇关于寻找最小的下一个更大的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!