jzhangnu / Leetcode-JS-Solutions

:tropical_drink: Leetcode solutions using JavaScript.
52 stars 7 forks source link

581. Shortest Unsorted Continuous Subarray #129

Open jzhangnu opened 6 years ago

jzhangnu commented 6 years ago
//发现顺序不对,进行替换
var findUnsortedSubarray= function(nums){
  var res = 0,
      start = -1,
      n = nums.length;

  for(var i=1; i<n; i++){
    if(nums[i] < nums[i-1]){
      var j = i;
      while(j>0 && nums[j]<nums[j-1]){
        [nums[j],nums[j-1]] = [nums[j-1],nums[j]]
        j--;
      }
      if(start==-1 || start>j)start = j
      res=Math.max(res,i-start+1)
    }
  }

  return res
}

//用一个辅助数组,分别从头和尾比较。
var findUnsortedSubarray= function(nums){
  var n = nums.length, i = 0, j = n - 1;
  var t = nums.slice();
  nums.sort();
  while(i < n && nums[i] == t[i])i++;
  while(j > i && nums[j] == t[j])j++;
  return j - i-1
}