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:

  1. Input: [2, 6, 4, 8, 10, 9, 15]
  2. Output: 5
  3. Explanation: You need to sort [6, 4, 8, 10, 9] in
  4. ascending order to make the whole array sorted in ascending order.

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @return {number}
  4. */
  5. var findUnsortedSubarray = function(nums) {
  6. // 左边的元素需要小于右边的
  7. let len = nums.length;
  8. let lIndex,
  9. rIndex;
  10. for ( let i = 0, m = len - 1; i < len; i++, m-- ) {
  11. // 左边的数
  12. if ( lIndex === undefined ) {
  13. for ( let j = i + 1; j < len; j++ ) {
  14. if ( nums[i] > nums[j] ) {
  15. lIndex = i;
  16. break;
  17. }
  18. }
  19. }
  20. // 右边的数
  21. if ( rIndex === undefined ) {
  22. for ( let n = m - 1 ; n >= 0; n-- ) {
  23. if ( nums[m] < nums[n] ) {
  24. rIndex = m+1;
  25. break;
  26. }
  27. }
  28. }
  29. }
  30. // 左边界和右边界都没有值,说明是升序
  31. if ( lIndex === undefined && rIndex === undefined ) return 0;
  32. return rIndex - lIndex
  33. };

这个实现有点挫。。。
Runtime: 428 ms, faster than 8.05% of JavaScript online submissions for Shortest Unsorted Continuous Subarray.