LeetCode_单调栈_中等_581.最短无序连续子数组

x33g5p2x  于2022-05-28 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(351)

1.题目

给你一个整数数组 nums ,你需要找出一个连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

请你找出符合题意的最短子数组并输出它的长度。

示例 1:
输入:nums = [2,6,4,8,10,9,15]
输出:5
解释:你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。

示例 2:
输入:nums = [1,2,3,4]
输出:0

示例 3:
输入:nums = [1]
输出:0

提示:
1 <= nums.length <= 104
-105 <= nums[i] <= 105

进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗?

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shortest-unsorted-continuous-subarray

2.思路

(1)排序

(2)单调栈

3.代码实现(Java)

  1. //思路1————排序
  2. public int findUnsortedSubarray(int[] nums) {
  3. int length = nums.length;
  4. //深拷贝一个新的数组 newNums
  5. int[] newNums = Arrays.copyOf(nums, length);
  6. //对数组 newNums 进行排序
  7. Arrays.sort(newNums);
  8. int left = 0, right = length - 1;
  9. //对比 nums 和 newNums,找出最短子数组的左右起点 left 和 right
  10. while (left < length && nums[left] == newNums[left]) {
  11. left++;
  12. }
  13. while (right >= 0 && nums[right] == newNums[right]) {
  14. right--;
  15. }
  16. return right - left + 1 <= 0 ? 0 : right - left + 1;
  17. }
  1. //思路2————单调栈
  2. public int findUnsortedSubarray(int[] nums) {
  3. int length = nums.length;
  4. int left = Integer.MAX_VALUE;
  5. int right = Integer.MIN_VALUE;
  6. //单调递增栈,存储元素索引
  7. Stack<Integer> incrStack = new Stack<>();
  8. for (int i = 0; i < length; i++) {
  9. while (!incrStack.isEmpty() && nums[incrStack.peek()] > nums[i]) {
  10. //栈中弹出的索引所对应的元素是乱序元素,其中最小的索引就是乱序子数组的左边界
  11. left = Math.min(left, incrStack.pop());
  12. }
  13. incrStack.push(i);
  14. }
  15. //单调递减栈,存储元素索引
  16. Stack<Integer> descStack = new Stack<>();
  17. for (int i = length - 1; i >= 0; i--) {
  18. while (!descStack.isEmpty() && nums[descStack.peek()] < nums[i]) {
  19. //栈中弹出的索引所对应的元素是乱序元素,其中最大的索引就是乱序子数组的右边界
  20. right = Math.max(right, descStack.pop());
  21. }
  22. descStack.push(i);
  23. }
  24. if (left == Integer.MAX_VALUE && right == Integer.MIN_VALUE) {
  25. //单调栈没有弹出任何元素,即数组 nums 本来就是有序的
  26. return 0;
  27. } else {
  28. return right - left + 1;
  29. }
  30. }

相关文章