Home LeetCode - 581. Shortest Unsorted Continuous Subarray
Post
Cancel

LeetCode - 581. Shortest Unsorted Continuous Subarray

581. Shortest Unsorted Continuous Subarray - Medium

문제

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

제한사항

  • 1 <= nums.length <= 104
  • -105 <= nums[i] <= 105

입출력 예

1
2
3
4
5
Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
1
2
3
4
Example 2:

Input: nums = [1,2,3,4]
Output: 0
1
2
3
4
Example 3:

Input: nums = [1]
Output: 0

풀이

  • Sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        std::vector<int> sorted = nums;
        std::sort(sorted.begin(), sorted.end());
        
        int start = 0;
        int last = nums.size() - 1;
        
        while(start < last) {
            if ((sorted[start] != nums[start]) &&
                (sorted[last] != nums[last])) {
                break;
            }
            
            if (sorted[start] == nums[start]) {
                ++start;
            }
            
            if (sorted[last] == nums[last]) {
                --last;
            }
        }
        
        return start == last ? 0 : last - start + 1;
    }
};
This post is licensed under CC BY 4.0 by the author.