Shortest Unsorted Continuous Subarray
Example 1:
Input: [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.思路:
O(nlogn) Java Implementation:
// 先复制数组,排序,找出最两边与原数组不同的index,中间即为所求的sequence
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] aux = nums.clone();
Arrays.sort(aux);
int left = -1, right = - 1;
for (int i = 0; i < aux.length; ++i) {
if (aux[i] != nums[i]) {
if (left == -1) left = i;
}
if (aux[nums.length - 1 - i] != nums[nums.length - 1 - i]) {
if (right == -1) right = nums.length - 1 - i;
}
if (left != -1 && right != -1) return right - left + 1;
}
return 0;
}
}O(N) Python Implementation:
更新

C++ Code:
Last updated