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.
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.
Example 2:
Input: nums = [1,2,3,4] Output: 0
Example 3:
Input: nums = [1] Output: 0
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
Follow up: Can you solve it in
O(n)
time complexity?
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
n = len(nums)
numsSorted = sorted(nums)
left, right = 0, n - 1
while left < n and nums[left] == numsSorted[left]:
left += 1
while right >= 0 and nums[right] == numsSorted[right]:
right -= 1
return 0 if right == -1 else right - left + 1
class Solution {
public int findUnsortedSubarray(int[] nums) {
int n = nums.length;
int[] numsSorted = new int[n];
System.arraycopy(nums, 0, numsSorted, 0, n);
Arrays.sort(numsSorted);
int left = 0, right = n - 1;
while (left < n && nums[left] == numsSorted[left]) {
left++;
}
while (right >= 0 && nums[right] == numsSorted[right]) {
right--;
}
return right == -1 ? 0 : right - left + 1;
}
}
func findUnsortedSubarray(nums []int) int {
n := len(nums)
maxn, minn := math.MinInt32, math.MaxInt32
left, right := -1, -1
for i := 0; i < n; i++ {
if maxn > nums[i] {
right = i
} else {
maxn = nums[i]
}
if minn < nums[n-i-1] {
left = n - i - 1
} else {
minn = nums[n-i-1]
}
}
if right == -1 {
return 0
}
return right - left + 1
}