arrays - 查找数组中的下一个最小值?
问题描述
这个问题一直困扰着我一段时间。基本上,如果您有一个输入数组 [4, 5, 2, 6, 7, 1],则 4 和 5 的下一个最小数字是 2,而 6 和 7 的下一个最小数字是 1。我需要识别这些较小的数字。我有一个明显的 n^2 及时解决方案,但我觉得有一个 O(n) 及时解决方案。我需要对右边的下一个最小数字的存在采取行动,并在右边没有更小的数字的情况下采取行动。
我尝试过考虑动态编程解决方案和数据结构(特别是堆栈),但我似乎无法同时检查正确性和 O(n) 时间复杂度,其中一个似乎对我来说失败了。
有什么帮助吗?
解决方案
您可以考虑为此使用堆栈数据结构。我已经用Java实现了它。这个想法是将索引推送到弹出,当堆栈中的顶部索引值大于数组的当前索引值时,弹出堆栈并将当前索引处的值分配给弹出的索引位置。
// Java Implementation of the idea
import java.util.Arrays;
import java.util.Stack;
public class NextSmallest{
public static void main(String[] args) {
int [] A = {4, 5, 2, 6, 7, 1};
int [] ret = nextSmallest(A);
System.out.println(Arrays.toString(ret)); // prints [2, 2, 1, 1, 1, 0]
}
static int [] nextSmallest(int [] A) {
Stack<Integer> stack = new Stack<>();
int n = A.length;
int [] nextSmallestIndex = new int[n];
for(int i = 0; i < n; i++) {
while(!stack.isEmpty() && A[stack.peek()] > A[i]) {
nextSmallestIndex[stack.pop()] = A[i];
}
stack.push(i);
}
return nextSmallestIndex;
}
}
推荐阅读
- julia - 从向量 for for 循环中提取值的问题
- django - django-import-export 库的 Django 外键问题(/import/ FOREIGN KEY 约束处的 IntegrityError 失败)
- python - Azure Functions - Python - AppInsights - 使用 opencensus 自定义维度
- java - 如何使用不同的参数在另一个构造函数中初始化私有变量
- swift - 使用 Swift 根据与设备位置的距离对对象列表进行排序
- javascript - 来自 JSON 的反应本机 SectionList 图像
- selenium-webdriver - 黄瓜并行 AbstractTestNGCucumberTests 上的 ElementClickInterceptedException
- python - 如何使用 Python 实现类似深度效果的 Photoshop“斜面/浮雕”?
- haskell - 无论如何我可以将“”(空格)添加到字符串值中吗
- javascript - 自动化下拉列表后,信息带来不同的日期格式