栈相关问题
单调栈
题目描述
返回数组中每个元素左边的元素中小于该元素的最近的元素位置,没有返回-1
题目解答
//使用单调栈
function getLeftCloseMax(array: number[]): number[] {
const res = [];
const temp = [];
array.forEach((item, index) => {
if (!temp.length) {
res.push(-1);
temp.push(index);
} else if (item > array[temp[temp.length - 1]]) {
res.push(temp[temp.length - 1]);
temp.push(index);
} else {
while (array[temp[temp.length - 1]] > item) {
temp.pop();
}
if (!temp.length) {
res.push(-1);
} else {
res.push(temp[temp.length - 1]);
}
temp.push(index);
}
});
return res;
}
const rest = getLeftCloseMax([3, 6, 8, 1, 0, 2]);