问题:Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < kand 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.
方法:
#include "Solution.h"
bool Solution::find132pattern1(vector<int>& nums){
int firstNum,secondNum,thirdNum;//定义局部变量,用于比较
if (nums.size() < 3)//数据少于3个时返回false
return false;
else{
for (int i = 0; i < (nums.size() - 2); i++){//从开始遍历到结尾
firstNum = nums[i];
secondNum = nums[i + 1];
thirdNum = nums[i + 2];
if (firstNum < thirdNum && thirdNum < secondNum)//若有132模式则返回true
return true;
}
}
return false;//若无132模式,遍历结束后返回false
}