2018-09-27 23:20:20
问题描述:
问题求解:
本题的难度还是有的,主要的考虑方向是尽量构造[min, max]来将后面出现的数字插入到其中。这里的求解方法是使用Stack来维护一组non-overlapping的区间,每次判断当前的数字能够加入到区间之中,如果可以,那么就直接返回true,如果不可以,那么就需要维护这个区间栈。这里有个地方需要注意到的是在栈顶的元素的左边界是到当前的为止的最小值,换句话说,Stack中的区间是按照左边界进行排序的。
public boolean find132pattern(int[] nums) {
Stack<int[]> stack = new Stack<>();
for (int i = 0; i < nums.length; i++) {
if (stack.isEmpty() || stack.peek()[0] > nums[i]) stack.push(new int[]{nums[i], nums[i]});
// 这里不能直接写else目的是为了过滤掉和当前min相等的数字
else if (stack.peek()[0] < nums[i]) {
if (stack.peek()[1] > nums[i]) return true;
else {
int[] last = stack.pop();
System.out.println(last[0] + " " + last[1]);
if (last[1] > nums[i]) return true;
last[1] = nums[i];
while (!stack.isEmpty() && stack.peek()[1] <= nums[i]) stack.pop();
if (!stack.isEmpty() && stack.peek()[0] < nums[i]) return true;
stack.push(last);
}
}
}
return false;
}