[算法分析与设计] leetcode 每周一题:132 Pattern

题目链接:https://leetcode.com/problems/132-pattern/description/

题目大意: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.


思路:

总的来说,算是用了贪心,维护一个second和third的变量,后遍历数组nums,遇到nums[i]比seond大的则third = second , second = a[i](极可能使得second 和third 大),一旦遇到nums[i] < third 则返回true. 不过这样有个问题,就是如果数组末尾是顺序变大的极大的数,即使前面有符合条件的a1,a2,a3,由于贪心,second,third也不会变,因此需要在外面加一层循环,虽说看上上是两层循环,不过只有在最坏的情况下才O(n2).只要最后一个数不是最大数,都会O(n).

代码:

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
       if(nums.size() < 3) return false;
       int second, third;

       for(int j = 0; j < nums.size() - 1; j++) {
            second = nums[nums.size() - j - 1];
            third = INT_MIN;
            for(int i = nums.size() - j - 2; i >= 0; i--) {
                if(nums[i] > second) {
                    third = second;
                    second = nums[i];
                } else if(third > nums[i])  {
                    return true;
                } 
            }
       }
       return false;
    }
};


猜你喜欢

转载自blog.csdn.net/liangtjsky/article/details/78712869