【12月22日】LeetCode刷题日志(六):132 Pattern
来源:互联网 发布:医学图像算法工程师 编辑:程序博客网 时间:2024/06/06 02:26
题目描述
Given a sequence of n integers a1, a2, …, an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
题目分析
该题题意不是很很难理解,就是在一个长度在15000内的数组中判断是否存在三个元素符合“132模式”。
o(n^3)
一个很容易想到的办法就是穷举所有的可能的三元素子数组,也就是三重循环可以得到:
public boolean find132pattern(int[] nums) { boolean flag = false; int len = nums.length; ko: for(int i=0;i<len-2;i++){ for(int j=i+1;j<len-1;j++){ for (int m=j+1;m<len;m++) if(nums[i]<nums[m] && nums[m]<nums[j]){ flag = true; break ko; } } } return flag; }
o(n^2)
进一步思考这个问题,要求找出132模式的{ai, aj, am}。为了降低复杂度,理论上要确定(*, *, *)这个三个未知数,就需要进行三次循环遍历,其解决方案就如上述,复杂度为o(n^3)。但是如果是(*, j,*)呢?接下来思考,如果j是固定的,如何确定i和m的值呢。
我们的限制条件中有ai < am < aj。也就是说ai和aj左边“边界”,再确定am。
- 第一步 (*, j,*) –>(i, j ,*)
- 第二步(i, j *) –>(i,j,m)
既然我们假定j是已经确定的,那么第一步先思考如何确定左边界i;常理上讲ai的值越小,那么下一步确定m的空间就越大。故在确定j之后,令i就是[0,j]之间的最小的元素对应的索引;第二步,如果可以顺利的找到符合的m,则结束,返回true;重复上述步骤,即可。
public boolean find132pattern3(int[] nums) { for (int j = 0, min = Integer.MAX_VALUE; j < nums.length; j++) { min = Math.min(nums[j], min);//min用于记录[0,j]的最小值 if (min == nums[j]) continue; for (int m = nums.length - 1; m > j; k--) { if (min < nums[m] && nums[m] < nums[j]) return true; } } return false; }