0%

shortest-unsorted-continuous-subarray

Shortest Unsorted Continuous Subarray – LeetCode 581

Problem

Description

Given an integer array, 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, too.

You need to find the shortest such subarray and output its length.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> sorted(nums.cbegin(), nums.cend());
sort(nums.begin(), nums.end());
unsigned left = 0, right = nums.size() - 1;
for(; left != nums.size() && sorted[left] == nums[left]; ++left) {}
while(left <= right && sorted[right] == nums[right]) --right;
return right - left + 1;
}
};

思路

先进行排序之后找出不同的连续部分即可。时间复杂度$O(nlog(n))$,空间复杂度$O(1)$。
耗时$32$ ms,排名$56.62\%$

Better

思路

直接扫描标记遍历过程中的反常元素范围。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$24$ ms,排名$2.21\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size(), start = -1, end = -2;
int mn = nums[n - 1], mx = nums[0];
for (int i = 1; i < n; ++i) {
mx = max(mx, nums[i]);
mn = min(mn, nums[n - 1 - i]);
if (mx > nums[i]) end = i;
if (mn < nums[n - 1 - i]) start = n - 1 - i;
}
return end - start + 1;
}
};