【发布时间】:2014-09-06 21:51:42
【问题描述】:
假设,给定一个整数数组 A,我想用 A 找出另一个 COUNT 数组。
例如,int A[] = {34, 10, 15, 14, 30, 27, 21, 32, 50}
对于上面的例子,COUNT[] 应该是:{0, 0, 1, 0, 3, 0, 0, 6, 8}
这里,COUNT[i]对应A[i],COUNT[i]表示A中小于A[i]的连续先前元素个数。
例如,A[1] = 10, COUNT[1] = 0,因为 A 中没有小于 A[1] 的前一个元素。
A[7] = 32, COUNT[7] = 6,因为 32 大于前 6 个连续元素(例如,10、15、14、30、27、21)。
我们可以为这个问题提供 O(n) 的解决方案吗?
编辑:
根据@user1990169 的算法, 我在 Java 中实现它如下,但它没有给出预期的输出,因为算法不计算堆栈上不存在的那些索引(在早期迭代中已经弹出)。
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<Integer>();
// int a[] = new int[] { 53, 2, 7, 5, 15, 12, 10, 38, 72 };
int a[] = new int[] { 34, 10, 15, 14, 30, 27, 21, 32, 50 };
int N = a.length;
int[] count = new int[N];
int tos = 0;
int poppedElemIdx = 0;
int popCount = 0;
boolean counted = false;
stack.clear();
for (int i = 0; i < N; i++) {
popCount = 0;
counted = false;
while (!stack.isEmpty()) {
tos = stack.peek();
if (a[tos] > a[i]) {
stack.push(i);
count[i] = count[poppedElemIdx] + popCount;
counted = true;
break;
}
poppedElemIdx = stack.pop();
popCount++;
// popCount += (count[poppedElemIdx] + 1);
}
if (counted) {
continue;
}
stack.push(i);
count[i] = popCount;
}
// Print count array
for (int i = 0; i < N; i++) {
System.out.print(count[i] + " ");
}
}
【问题讨论】:
标签: arrays algorithm data-structures