You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
const arr = [2, 1, 2, 4, 3];
function test(arr) {
let len = arr.length;
let left = 0;
let right = len - 1;
const result = [];
let myBeIndex;
let inserted = false;
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
left = i + 1;
right = len - 1;
inserted = false;
while (left <= right) {
if (arr[left] > element) {
result.push(arr[left]);
inserted = true;
right = len - 1;
break;
}
if (arr[right] > element) {
myBeIndex = right;
}
left++;
right--;
}
if (myBeIndex) {
result.push(arr[myBeIndex]);
inserted = true;
myBeIndex = null;
}
if (!inserted) {
result.push(-1);
}
}
return result;
}
console.log(test(arr));
// 暴力法
function test (ary) {
let result = []
for(let i = 0; i < ary.length; i++) {
let value = ary[i]
let j = i + 1
while(j < ary.length) {
if(ary[j] > ary[i]) {
result.push(ary[j])
break
}else {
j++
}
}
if(!result[i]){
result[i] = -1
}
}
return result
}
console.log(test([2,1,2,4,3]))
function getFistMax(nums){
let res = new Array(nums.length).fill(-1)
let stack = []
for(let i=0;i<nums.length;i++){
while(stack.length&&nums[i]>nums[stack[stack.length-1]]){
let top = stack.pop()
res[top] = nums[i]
}
stack.push(i)
}
return res
}
console.log(getFistMax([2,1,2,4,3]))
Activity
gaowujian commentedon Dec 28, 2020
hundren commentedon Dec 28, 2020
linlinyang commentedon Dec 28, 2020
时间复杂度O(n)
空间复杂度L(n)
mx52jing commentedon Dec 28, 2020
sunsmeil commentedon Dec 28, 2020
sunsmeil commentedon Dec 28, 2020
yokots commentedon Jan 2, 2021
skychx commentedon Apr 13, 2021
这个应该放在数据结构「栈」里,这道题其实考察的是单调栈,原题其实是 LeetCode 503: 下一个更大元素 II
skychx commentedon Apr 13, 2021
xllpiupiu commentedon Oct 6, 2021
AlexZhang11 commentedon May 24, 2024
function getFistMax(nums){ let res = new Array(nums.length).fill(-1) let stack = [] for(let i=0;i<nums.length;i++){ while(stack.length&&nums[i]>nums[stack[stack.length-1]]){ let top = stack.pop() res[top] = nums[i] } stack.push(i) } return res } console.log(getFistMax([2,1,2,4,3]))