[LeetCode] 581. Shortest Unsorted Continuous Subarray(最短无序的连续子数组)
-
Difficulty: Medium
-
Related Topics: Array
-
Link: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
Description
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.
给定一个整数数组 nums
,你需要找到这样一个连续子数组,只要将这个子数组排序,整个数组就成为有序的。
Return the shortest such subarray and output its length.
找到符合上述条件的最短子数组,并返回它的长度。
Examples
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 <= 1e4
-1e5 <= nums[i] <= 1e5
Solution
第一直觉是排序后一个个比较,然后我就 AC 了(什么鬼?)代码如下:
class Solution {
fun findUnsortedSubarray(nums: IntArray): Int {
if (nums.size < 2) {
return 0
}
val sorted = nums.sorted()
var left = 0
var right = nums.lastIndex
for (i in nums.indices) {
if (nums[i] == sorted[i]) {
left++
} else {
break
}
}
for (i in nums.indices.reversed()) {
if (nums[i] == sorted[i]) {
right--
} else {
break
}
}
return if (left >= right) {
0
} else {
right - left + 1
}
}
}