Question:
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.
Example:
Input: [2, 6, 4, 8, 10, 9, 15]Output: 5Explanation: You need to sort [6, 4, 8, 10, 9] inascending order to make the whole array sorted in ascending order.
Solution:
/*** @param {number[]} nums* @return {number}*/var findUnsortedSubarray = function(nums) {// 左边的元素需要小于右边的let len = nums.length;let lIndex,rIndex;for ( let i = 0, m = len - 1; i < len; i++, m-- ) {// 左边的数if ( lIndex === undefined ) {for ( let j = i + 1; j < len; j++ ) {if ( nums[i] > nums[j] ) {lIndex = i;break;}}}// 右边的数if ( rIndex === undefined ) {for ( let n = m - 1 ; n >= 0; n-- ) {if ( nums[m] < nums[n] ) {rIndex = m+1;break;}}}}// 左边界和右边界都没有值,说明是升序if ( lIndex === undefined && rIndex === undefined ) return 0;return rIndex - lIndex};
这个实现有点挫。。。
Runtime: 428 ms, faster than 8.05% of JavaScript online submissions for Shortest Unsorted Continuous Subarray.
