我在求职面试中得到了这个问题,我无法解决 我觉得我真的很紧张,因为它看起来并不那么难。
Arr是给定的整数数组,大小为n。 Sol是一个给定的空数组, 大小n。
对于每个i(我从0到n-1)你必须把索引放在Sol [i]中 在Arr中最近的元素出现在左侧,这是更小的 比Arr [i]。含义:Sol [i] = max {j | j<一世; Arr [j]< Arr [i]}。如果 没有这样的索引,放-1。
例如:Arr是[5,7,9,2,8,11,16,10,12] Sol是 [-1,0,1,-1,3,4,5,4,7]
时间复杂度:o(n)空间复杂度:o(n)
我尝试从最后到开始扫描数组,但我不知道如何继续。
我被要求只使用数组和链表。 我有10分钟的时间来解决它,所以猜不是那么难。
非常感谢!!
答案 0 :(得分:1)
注意,对于长度<&lt;的Arr [] 2有一些简单的解决方案。该伪代码假定Arr []的长度> = 2。
int Arr[] = {5,7,9,2,8,11,16,10,12};
int Sol[] = new int[9];
Stack<int> undecided; // or a stack implemented using a linked list
Sol[0] = -1; // this is a given
for(int i = Arr.length() - 1; i != 0; --i) {
undecided.push(i); // we haven't found a smaller value for this Arr[i] item yet
// note that all the items already on the stack (if any)
// are smaller than the value of Arr[i] or they would have
// been popped off in a previous iteration of the loop
// below
while (!undecided.empty() && (Arr[i-1] < Arr[undecided.peek()])) {
// the value for the item on the undecided stack is
// larger than Arr[i-1], so that's the index for
// the item on the undecided stack
Sol[undecided.peek()] = i-1;
undecided.pop();
}
}
// We've filled in Sol[] for all the items have lesser values to
// the left of them. Whatever is still on the undecided stack
// needs to be set to -1 in Sol
while (!undecided.empty()) {
Sol[undecided.peek()] = -1;
undecided.pop();
}
说实话,我不确定在面试时间为10分钟的情况下我会想出这个。
可以在ideone.com上找到C ++版本:https://ideone.com/VXC0yq
答案 1 :(得分:0)
int Arr[] = {5,7,9,2,8,11,16,10,12};
int Sol[] = new int[9];
for(int i = 0; i < Arr.length; i++) {
int element = Arr[i];
int tmp = -1;
for(int j = 0 ;j < i; j++) {
int other = Arr[j];
if (other < element) {
tmp = j;
}
}
Sol[i] = tmp;
}