Skip to content

Commit 0672d26

Browse files
committed
Add solution #581
1 parent 2a35f24 commit 0672d26

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,7 @@
453453
572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy|
454454
575|[Distribute Candies](./0575-distribute-candies.js)|Easy|
455455
576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium|
456+
581|[Shortest Unsorted Continuous Subarray](./0581-shortest-unsorted-continuous-subarray.js)|Medium|
456457
589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy|
457458
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
458459
599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy|
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 581. Shortest Unsorted Continuous Subarray
3+
* https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums, you need to find one continuous subarray such that if you
7+
* only sort this subarray in non-decreasing order, then the whole array will be sorted
8+
* in non-decreasing order.
9+
*
10+
* Return the shortest such subarray and output its length.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @return {number}
16+
*/
17+
var findUnsortedSubarray = function(nums) {
18+
let start = -1;
19+
let end = -2;
20+
21+
for (let i = 1, min = nums[nums.length - 1], max = nums[0]; i < nums.length; i++) {
22+
max = Math.max(max, nums[i]);
23+
min = Math.min(min, nums[nums.length - 1 - i]);
24+
if (nums[i] < max) {
25+
end = i;
26+
}
27+
if (nums[nums.length - 1 - i] > min) {
28+
start = nums.length - 1 - i;
29+
}
30+
}
31+
32+
return end - start + 1;
33+
};

0 commit comments

Comments
 (0)