[LeetCode] Shortest Unsorted Continuous Subarray

581. Shortest Unsorted Continuous Subarray

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
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> sortedNums(nums.begin(), nums.end());
sort(sortedNums.begin(), sortedNums.end());
int start = 0 , end = nums.size() - 1;
for(; start < nums.size() && nums[start] == sortedNums[start]; start++) {}
for(; end >= 0 && nums[end] == sortedNums[end]; end--) {}
return start > end ? 0 : end - start + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/11/PS/LeetCode/shortest-unsorted-continuous-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.