1. 程式人生 > >LC 456. 132 Pattern

LC 456. 132 Pattern

div lan att sig 大於 算法 return data memory

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; } };

LC 456. 132 Pattern