查找最接近的大于当前数字的数字的索引
Find the index of the closest number that is greater than the current number
对于正整数数组中的每个整数,找到最接近的大于当前整数的整数的索引。此外,我们只需要在当前整数的左边搜索答案。
例如
Input array - [ 5, 4, 3, 6, 2, 3]
Output array - [ -1, 0, 1, -1, 3, 3]
给那些没有答案的数字加-1。
有一个简单的O(n^2(方法,对于每个数字,从上一个数字到数组的开头运行for循环。
for(int i=0; i<n; ++i)
{
output[i] = -1;
for(int j=i-1; j>=0; --j)
{
if(input[j] > input[i])
{
output[i] = j;
break;
}
}
}
当"n"较大时,此方法效率低下。有没有更有效的方法?
我相信一个流行的O(n)
解决方案是使用堆栈,保持降序(希望算法从注释的代码中足够清晰(:
function f(A){
let stack = []
let output = []
for (let i=0; i<A.length; i++){
// While there are lower or
// equal elements on top of
// the stack
while (stack.length && A[ stack[stack.length-1] ] <= A[i])
stack.pop();
// The next greater element
// to the left
if (stack.length)
output.push(stack[stack.length-1]);
// There was none
else
output.push(-1);
stack.push(i);
}
return output;
}
var As = [
[5, 4, 3, 6, 2, 3],
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[0, 3, -1, 5, 4]
];
for (let A of As){
console.log(`${ A }`);
console.log(`${ f(A) }`);
console.log('');
}
建议的答案是:https://www.geeksforgeeks.org/find-the-nearest-smaller-numbers-on-left-side-in-an-array/
其主要思想是使用堆栈来记住处理后的值。在链接中,他们关心值,但它可以很容易地适应输出索引。
#include <iostream>
#include <vector>
#include <stack>
std::vector<int> function(std::vector<int> input) {
std::vector<int> output;
output.reserve(input.size());
// Create an empty stack
// first element of the pair is the index. second is the value
std::stack<std::pair<int,int>> S;
// Traverse all array elements
for (int i=0; i<input.size(); i++)
{
// Keep removing top element from S while the top
// element is less than or equal to arr[i]
while (!S.empty() && S.top().second <= input[i])
S.pop();
// If all elements in S were greater than arr[i]
if (S.empty())
output.push_back(-1);
else //Else print the nearest smaller element
output.push_back(S.top().first);
// Push this element
S.push({i, input[i]});
}
return output;
}
int main() {
std::vector<int> input{5, 4, 3, 6, 2, 3};
std::vector<int> output = function(input);
for(int index : output) {
std::cout << index << ' ';
}
return 0;
}
输出:
-1 0 1 -1 3 3
编译器资源管理器:https://godbolt.org/z/8W3ecv
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 数组索引的值没有增加
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 查找最接近的大于当前数字的数字的索引
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- 查找数组中重复(重复)数字的索引
- 如何以正确的时区从XTS索引中获取数字时间?
- 根据另一个数字的可整除性返回子数组中的索引
- 使用二叉搜索查找数字的第 N 次出现的索引
- 循环并将数字的索引用作文件名
- 尝试为数字值编制索引。C++ & Lua
- 尝试将数字乘以其索引
- 对数字及其索引列表进行排序的最快方法
- 为什么我可以索引到数字超出范围的三维数组中,但仍然可以访问数组中的最后一个数字
- 带有Overload[]运算符的C++MyInteger类,因此索引在位置i返回数字
- 如果用户从数组中输入数字,如何获取 2D 数组的索引
- 将数组中的所有数字更改为其索引值
- 用户正在输入10个数字,找到最大的负值及其索引/位置