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:

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

Note:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

Idea 1. Similar to Max Chunks To Make Sorted II LT768, find the chunks and merge chunks by updating the end index, start index is the staring point of first chunk, the lengh = end index - start index.

The key point is: The array is considered sorted if the left elements are smaller or equal than the right elements, that is, the maximum of the left subarray is smaller or equal than the minimum of the right subarray.

The unsorted chunks can be found by:

a. store the minValue from right to left

b. stack in ascending order.

Time complexity: O(n)

Space complexity: O(n)

1.a

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. int sz = nums.length;
  4. int[] rightMin = new int[sz];
  5. rightMin[sz-1] = nums[sz-1];
  6.  
  7. for(int i = sz-2; i >= 0; --i) {
  8. rightMin[i] = Math.min(rightMin[i+1], nums[i]);
  9. }
  10.  
  11. int startIndex = -1;
  12. int endIndex = -1;
  13. int currMax = Integer.MIN_VALUE;
  14. for(int i = 0; i + 1 < sz; ++i) {
  15. currMax = Math.max(currMax, nums[i]);
  16.  
  17. if(currMax > rightMin[i+1]) {
  18. if(startIndex == -1) {
  19. startIndex = i; // first unsorted chunk
  20. }
  21. else {
  22. endIndex = -1; // new unsorted chunk, mark endIndex = -1 to merge
  23. }
  24. }
  25. else if(startIndex != -1 && endIndex == -1){
  26. endIndex = i; // if curMax <= rightMin[i+1], means nums(i+1...end) is sorted
  27. }
  28. }
  29.  
  30. if(startIndex == -1) {
  31. return 0;
  32. }
  33.  
  34. if(endIndex == -1) {
  35. endIndex = sz - 1;
  36. }
  37.  
  38. return endIndex - startIndex + 1;
  39. }
  40. }

1.b stack

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. Deque<Integer> ascendingStack = new LinkedList<>();
  4.  
  5. int startIndex = nums.length;
  6. int endIndex = -1;
  7. int currMaxIndex = 0;
  8. for(int i = 0; i < nums.length; ++i) {
  9. if(currMaxIndex == nums.length || nums[currMaxIndex] < nums[i] ) {
  10. currMaxIndex = i;
  11. }
  12. while(!ascendingStack.isEmpty() && nums[ascendingStack.peek()] > nums[i]) {
  13. startIndex = Math.min(startIndex, ascendingStack.pop()); // unsorted chunk
  14. endIndex = -1;
  15. }
  16. ascendingStack.push(currMaxIndex);
  17. if(startIndex != nums.length && endIndex == -1) {
  18. endIndex = i; // the end of unsorted chunk: the current index i
  19. }
  20. }
  21.  
  22. if(startIndex == nums.length) {
  23. return 0; // the array is sorted
  24. }
  25.  
  26. return endIndex - startIndex + 1;
  27. }
  28. }

Idea 2. The boundary of unsorted subarray is determined by the leftmost and rightmost elements not in the correct position(the sorted position). Borrow the idea from selection sort, for any pair of integeras (0 < i < j < nums.length), if num[i] > nums[j],  this pair will get swapped to get the right position for the sorted array, since we only require the bounday, there is no need to sort it, just note down the index of elements which mark the boundary of the unsorted subarray. Hence, out of all pairs, the leftmost index i not at it's correct position is the left boundary, the rightmost index j is the right boundary.

Time complexity: O(n2)

Space complexity: O(1)

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. int startIndex = nums.length;
  4. int endIndex = -1;
  5.  
  6. for(int i = 0; i < nums.length; ++i) {
  7. for(int j = i; j < nums.length; ++j) {
  8. if(nums[i] > nums[j]) {
  9. startIndex = Math.min(startIndex, i);
  10. endIndex = Math.max(endIndex, j);
  11. }
  12. }
  13. }
  14.  
  15. if(startIndex == nums.length) {
  16. return 0;
  17. }
  18.  
  19. return endIndex - startIndex + 1;
  20. }
  21. }

Idea 3. Comparing with the correct position in the sorted array, mark down the leftmost index and rightmost index different from the sorted position.

Time complexity: O(nlogn)

Space complexity: O(n)

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. int[] numsSorted = Arrays.copyOf(nums, nums.length);
  4.  
  5. Arrays.sort(numsSorted);
  6.  
  7. int startIndex = nums.length;
  8. int endIndex = -1;
  9. for(int i = 0; i < nums.length; ++i) {
  10. if(nums[i] != numsSorted[i]) {
  11. startIndex = Math.min(startIndex, i);
  12. endIndex = Math.max(endIndex, i);
  13. }
  14. }
  15.  
  16. if(startIndex == nums.length) {
  17. return 0;
  18. }
  19.  
  20. return endIndex - startIndex + 1;
  21. }
  22. }

Idea 4. The correct position of the minimum element in the unsorted subarray determins the left boundary, the correct position of the maximum element in the unsorted subarray determins the right boundary. Two steps: 1. Find the unsorted subarray 2. find the minimum and maximum

a. stack in ascending order for min, in descending order for maxmum

While traversing over the nums array starting from the begining, pushing elements over the stack if in asecending order, otherwise in a falling slope(unsorted subarray), an element nums[j] smaller than the element on the top of the stack, poping elements in the stack until the elemnts on the top is equal or smaller than nums[j], the last poped element is the correct position for nums[j]. For all the nums[j] not in correct position, the minmum of the correct positions determins the left boundary.

Time complexity: O(n)

Space complexity: O(n)

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. Deque<Integer> indexStack = new LinkedList<>();
  4.  
  5. int startIndex = nums.length;
  6. int endIndex = -1;
  7. for(int i = 0; i < nums.length; ++i) {
  8. while(!indexStack.isEmpty() && nums[indexStack.peek()] > nums[i]) {
  9. startIndex = Math.min(startIndex, indexStack.pop());
  10. }
  11. indexStack.push(i);
  12. }
  13.  
  14. for(int i = nums.length-1; i >= 0; --i) {
  15. while(!indexStack.isEmpty() && nums[i] > nums[indexStack.peek()]) {
  16. endIndex = Math.max(endIndex, indexStack.pop());
  17. }
  18. indexStack.push(i);
  19. }
  20.  
  21. if(startIndex == nums.length) {
  22. return 0;
  23. }
  24.  
  25. return endIndex - startIndex + 1;
  26. }
  27. }

b. without extra space, rising slope starting from the begining, falling slope staring from the end

Time complexity: O(n)

Space complexity: O(1)

  1. C1 class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. int startIndex = 0;
  4.  
  5. while(startIndex+1 < nums.length && nums[startIndex] <= nums[startIndex+1]) {
  6. ++startIndex;
  7. }
  8.  
  9. if(startIndex == nums.length-1) {
  10. return 0;
  11. }
  12.  
  13. int minItem = nums[startIndex+1];
  14. for(int i = startIndex+1; i < nums.length; ++i) {
  15. minItem = Math.min(minItem, nums[i]);
  16. }
  17.  
  18. // nums[0..startIndex] is sorted,
  19. // the correct position is the index of the first element bigger than minItem
  20. // from 0 to startIndex (left to right)
  21. for(int i = 0; i <= startIndex; ++i) {
  22. if(nums[i] > minItem) {
  23. startIndex = i;
  24. break;
  25. }
  26. }
  27.  
  28. int endIndex = nums.length-1;
  29. while(endIndex-1 >= 0 && nums[endIndex-1] <= nums[endIndex]) {
  30. --endIndex;
  31. }
  32.  
  33. int maxItem = nums[endIndex-1];
  34. for(int i = endIndex-1; i >= 0; --i) {
  35. maxItem = Math.max(maxItem, nums[i]);
  36. }
  37.  
  38. // nums[endIndex, nums.length-1] is sorted
  39. // the correct position of the index of the first element smaller than maxItem
  40. // from nums.length-1 to endIndex (right to left)
  41. for(int i = nums.length-1; i>= endIndex; --i) {
  42. if(nums[i] < maxItem) {
  43. endIndex = i;
  44. break;
  45. }
  46. }
  47.  
  48. return endIndex - startIndex + 1;
  49. }
  50. }

Find the first unsorted subarray and the minimum element can be combine in one loop to make code more concise.

  1. class Solution {
  2. public int findUnsortedSubarray(int[] nums) {
  3. int minItem = Integer.MAX_VALUE;
  4.  
  5. boolean isSorted = true;
  6. for(int i = 1; i < nums.length; ++i){
  7. if(nums[i-1] > nums[i]) {
  8. isSorted = false;
  9. }
  10.  
  11. if(!isSorted) {
  12. minItem = Math.min(minItem, nums[i]);
  13. }
  14. }
  15.  
  16. if(isSorted) {
  17. return 0;
  18. }
  19.  
  20. int startIndex = 0;
  21. for(; startIndex < nums.length; ++startIndex) {
  22. if(nums[startIndex] > minItem) {
  23. break;
  24. }
  25. }
  26.  
  27. int maxItem = Integer.MIN_VALUE;
  28. isSorted = true;
  29. for(int i = nums.length-2; i >= 0; --i) {
  30. if(nums[i] > nums[i+1]) {
  31. isSorted = false;
  32. }
  33.  
  34. if(!isSorted) {
  35. maxItem = Math.max(maxItem, nums[i]);
  36. }
  37. }
  38.  
  39. int endIndex = nums.length-1;
  40. for(;endIndex >= 0; --endIndex) {
  41. if(nums[endIndex] < maxItem) {
  42. break;
  43. }
  44. }
  45.  
  46. return endIndex - startIndex + 1;
  47. }
  48. }

Shortest Unsorted Continuous Subarray LT581的更多相关文章

  1. LeetCode 581. 最短无序连续子数组(Shortest Unsorted Continuous Subarray)

    581. 最短无序连续子数组 581. Shortest Unsorted Continuous Subarray 题目描述 给定一个整型数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序 ...

  2. 【leetcode_easy】581. Shortest Unsorted Continuous Subarray

    problem 581. Shortest Unsorted Continuous Subarray 题意:感觉题意理解的不是非常明白. solution1: 使用一个辅助数组,新建一个跟原数组一模一 ...

  3. LeetCode 581. Shortest Unsorted Continuous Subarray (最短无序连续子数组)

    Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...

  4. [LeetCode] Shortest Unsorted Continuous Subarray 最短无序连续子数组

    Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...

  5. [Swift]LeetCode581. 最短无序连续子数组 | Shortest Unsorted Continuous Subarray

    Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...

  6. Leeetcode--581. Shortest Unsorted Continuous Subarray

    Given an integer array, you need to find one continuous subarray that if you only sort this subarray ...

  7. 581. Shortest Unsorted Continuous Subarray

      Given an integer array, you need to find one continuous subarray that if you only sort this subarr ...

  8. 581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况

    [抄题]: Given an integer array, you need to find one continuous subarray that if you only sort this su ...

  9. LeetCode581. Shortest Unsorted Continuous Subarray

    Description Given an integer array, you need to find one continuous subarray that if you only sort t ...

随机推荐

  1. Eclipse git 冲突合并

    Eclipse有一个git的插件叫EGit,用于实现本地代码和远程代码对比.合并以及提交.但是在本地代码和远程代码有冲突的时候,EGit的处理方案还是有点复杂.今天就彻底把这些步骤给理清楚,并公开让一 ...

  2. Mono vs IL2CPP

    [Mono vs IL2CPP]             参考:http://blog.csdn.net/gz_huangzl/article/details/52486255

  3. Javascript Iterator

    [Javascript Iterator] 1.@@iterator Whenever an object needs to be iterated (such as at the beginning ...

  4. 【Scheme】Huffman树

    (define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car objec ...

  5. STL::unordered_map/unordered_multimap

    unordered_map: 和 unorder_set 相似,该容器内部同样根据 hash value 把键值对存放到相应的 bucket(slot)中,根据单个 key 来访问 value 的速度 ...

  6. centos 6.9 +nginx 配置GIT HTTPS服务器(证书采用自签名)

    第一部分原通过SSH访问的GIT服务器迁移 1.把原服务器GIT资源库目录完成复制至新的服务器 2.安装GIT服务器 新的服务器 创建用户 useradd git password git 下载GIT ...

  7. NumPy 矩阵库(Matrix)

    NumPy 矩阵库(Matrix) NumPy 中包含了一个矩阵库 numpy.matlib,该模块中的函数返回的是一个矩阵,而不是 ndarray 对象. 一个 的矩阵是一个由行(row)列(col ...

  8. 十个前端UI优秀框架

    最近需要一些前端框架,于是在网上整理了一些感觉不错的前端框架,有pc端和移动端,为了方便日后自己先记录下来了... Bootstrap 首先说 Bootstrap,估计你也猜到会先说或者一定会有这个( ...

  9. C++中 top()与pop()

    top()是取出栈顶元素,不会删掉栈里边的元素 pop()是删除栈顶元素.

  10. Angular之响应式表单 ( Reactive Forms )

    项目结构 一 首页 ( index.html ) <!doctype html> <html lang="en"> <head> <met ...