LC 456. 132 Pattern

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.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
检测:更准确地说,我们在搜索左侧有效的s1候选者时,跟踪每个有效(s2> s3)组合的s3的最大值。一旦我们遇到左边的任何数字小于我们到目前为止看到的最大s3,我们就知道我们找到了一个有效的序列,因为s1 <s3意味着s1 <s2。
 
算法:我们可以从任何一方开始,但是从右边开始可以一次扫描就做完。我们的想法是从最右边开始并搜索有效的(s2,s3)对,只需要记住最大的有效s3值,使用堆栈将有效用于此目的(堆里的所有值是s2,均大于s3)。如果左边有任何数字大于它,则数字成为s3的候选者。
 
正确性:当我们从右向左扫描时,我们可以轻松地跟踪到目前为止遇到的所有(s2,s3)候选者的最大s3值。因此,每当我们将nums [i]与区间nums [i + 1] ... nums [n-1]中s3的最大候选者进行比较时,我们实际上会问这样的问题:是否有任何132序列,其中s1 = nums [i]?因此,如果函数返回false,则必须没有132序列。
 
实现:
 
有一个堆栈,每次我们存储一个新号码时,我们首先会弹出小于该号码的所有号码。弹出的数字成为s3的候选者。
我们跟踪这样的s3的最大值(它始终是堆栈中最近弹出的数字)。
一旦我们遇到任何小于s3的数字,我们就知道我们找到了一个有效的序列,因为s1 <s3意味着s1 <s2。
RUNTIME:每个项目最多被推送一次,因此时间复杂度为O(n)。
Runtime:  24 ms, faster than 57.41% of C++ online submissions for 132 Pattern.
Memory Usage:  7.5 MB, less than 0.67% of C++ online submissions for 132 Pattern.
class Solution {
public:
  bool find132pattern(vector<int>& nums) {
    int third = INT32_MIN;
    stack<int> s;
    for(int i=nums.size()-1; i>=0; i--) {
      if(nums[i] < third) return true;
      while(!s.empty() && nums[i] > s.top()) {
        third = s.top();
        s.pop();
      }
      s.push(nums[i]);
    }
    return false;
  }
};

猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10355805.html