Skip to content

Commit 5f3859c

Browse files
author
王鹏
committed
feat(EASY): add _581_findUnsortedSubarray
1 parent 3a61124 commit 5f3859c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package pp.arithmetic.leetcode;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* Created by wangpeng on 2019-09-12.
7+
* 581. 最短无序连续子数组
8+
* <p>
9+
* 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
10+
* <p>
11+
* 你找到的子数组应是最短的,请输出它的长度。
12+
* <p>
13+
* 示例 1:
14+
* <p>
15+
* 输入: [2, 6, 4, 8, 10, 9, 15]
16+
* 输出: 5
17+
* 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
18+
* 说明 :
19+
* <p>
20+
* 输入的数组长度范围在 [1, 10,000]。
21+
* 输入的数组可能包含重复元素 ,所以升序的意思是<=。
22+
* <p>
23+
* 来源:力扣(LeetCode)
24+
* 链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
25+
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
26+
*/
27+
public class _581_findUnsortedSubarray {
28+
29+
public static void main(String[] args) {
30+
_581_findUnsortedSubarray findUnsortedSubarray = new _581_findUnsortedSubarray();
31+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{2, 6, 4, 8, 10, 9, 15}));
32+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{8, 6, 4, 8, 10, 9, 15}));
33+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{2, 3, 3, 2, 4}));
34+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{1, 3, 2, 2, 2}));
35+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{1, 1}));
36+
System.out.println(findUnsortedSubarray.findUnsortedSubarray(new int[]{1, 2, 4, 5, 3}));
37+
}
38+
39+
/**
40+
* 解题思路:
41+
* 核心是我们需要找到无序子数组中最小元素和最大元素分别对应的正确位置
42+
*
43+
* @param nums
44+
* @return
45+
*/
46+
public int findUnsortedSubarray(int[] nums) {
47+
Stack<Integer> stack = new Stack<>();
48+
int l = nums.length, r = 0;
49+
for (int i = 0; i < nums.length; i++) {
50+
while (!stack.isEmpty() && nums[stack.peek()] > nums[i])
51+
l = Math.min(l, stack.pop());
52+
stack.push(i);
53+
}
54+
stack.clear();
55+
for (int i = nums.length - 1; i >= 0; i--) {
56+
while (!stack.isEmpty() && nums[stack.peek()] < nums[i])
57+
r = Math.max(r, stack.pop());
58+
stack.push(i);
59+
}
60+
return r - l > 0 ? r - l + 1 : 0;
61+
}
62+
}

0 commit comments

Comments
 (0)