classSolution{public:boolfind132pattern(vector<int>&nums){stack<int>stack;// max stackintak=INT_MIN;// we want to find a seq ai < ak < ajfor(inti=nums.size()-1;i>=0;--i){// ai < ak, we're done because ai must also smaller than ajif(nums[i]<ak)returntrue;while(!stack.empty()&&stack.top()<nums[i])ak=stack.top(),stack.pop();stack.push(nums[i]);// nums[i] is a candidate of aj}returnfalse;}};
JAVA
classSolution{publicbooleanfind132pattern(int[]nums){Deque<Integer>stack=newArrayDeque<>();// max stackintak=Integer.MIN_VALUE;// we want to find a seq ai < ak < ajfor(inti=nums.length-1;i>=0;--i){if(nums[i]<ak)// ai < ak, we're done because ai must also smaller than ajreturntrue;while(!stack.isEmpty()&&stack.peek()<nums[i])ak=stack.pop();stack.push(nums[i]);// nums[i] is a candidate of aj}returnfalse;}}
Login to Codeflu
Log in to stay update and get notify on new arrivals.