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.
找出最短無排序的子陣列
Input: nums = [2,6,4,8,10,9,15]
Output: 5
Input: nums = [1,2,3,4]
Output: 0
Input: nums = [1]
Output: 0
複製排序後的陣列,與原陣列比較元素的不同,從頭搜尋,遇到第一個不同的元素,紀錄索引值start
,從尾搜尋,遇到第一個不同的元素,紀錄索引值end
,藉由start
與end
可算出陣列的長度。
var findUnsortedSubarray = function (nums) {
let len = nums.length;
let nums1 = nums.map(x => x).sort((x, y) => x - y);
let start = 0;
let end = 0;
let x = 1;
let y = 1;
for (let i = 0; i < len; i++) {
if (nums1[i] !== nums[i] && x) {
start = i;
x = 0;
}
if (nums1[len - i - 1] !== nums[len - i - 1] && y) {
end = len - i - 1;
y = 0;
}
}
return (start || end) ? end - start + 1 : 0;
};