Skip to content

Commit 45280dd

Browse files
authored
Create 581-shortest-unsorted-continuous-subarray.js
1 parent a9d02a6 commit 45280dd

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const findUnsortedSubarray = function(nums) {
6+
let stack = []
7+
let left = nums.length
8+
let right = 0
9+
for(let i = 0; i < nums.length; i++) {
10+
while(stack.length > 0 && nums[stack[stack.length - 1]] > nums[i]) {
11+
left = Math.min(left, stack.pop())
12+
}
13+
stack.push(i)
14+
}
15+
stack = []
16+
for(let i = nums.length - 1; i >= 0; i--) {
17+
while(stack.length > 0 && nums[stack[stack.length - 1]] < nums[i] ) {
18+
right = Math.max(right, stack.pop())
19+
}
20+
stack.push(i)
21+
}
22+
23+
24+
return right > left ? right - left + 1: 0
25+
};

0 commit comments

Comments
 (0)