LeetCode #456 132 Pattern 132模式 456 132 Pattern 132模式

456 132 Pattern 132模式

Description:
Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise, return false.

Follow up:
The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution?

Example:

Example 1:

Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: nums = [-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].

Constraints:

n == nums.length
1 <= n <= 10^4
-10^9 <= nums[i] <= 10^9

題目描述:
給定一個整數序列:a1, a2, ..., an,一個132模式的子序列 ai, aj, ak 被定義爲:當 i < j < k 時,ai < ak < aj。設計一個算法,當給定有 n 個數字的序列時,驗證這個序列中是否含有132模式的子序列。

注意:
n 的值小於15000。

示例 :

示例1:

輸入: [1, 2, 3, 4]

輸出: False

解釋: 序列中不存在132模式的子序列。

示例 2:

輸入: [3, 1, 4, 2]

輸出: True

解釋: 序列中有 1 個132模式的子序列: [1, 4, 2].

示例 3:

輸入: [-1, 3, 2, 0]

輸出: True

解釋: 序列中有 3 個132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0].

思路:

用單調棧記錄
cur記錄模式中的 ‘2’, 單調棧記錄模式中的 ‘3’
時間複雜度O(n), 空間複雜度O(n), 數組元素最多出入一次棧

代碼:
C++:

class Solution 
{
public:
    bool find132pattern(vector<int>& nums) 
    {
        stack<int> s;
        int cur = INT_MIN, n = nums.size();
        for (int i = n - 1; i > -1; i--)
        {
            if (cur > nums[i]) return true;
            while (!s.empty() and nums[i] > s.top())
            {
                cur = s.top();
                s.pop();
            }
            s.push(nums[i]);
        }
        return false;
    }
};

Java:

class Solution {
    public boolean find132pattern(int[] nums) {
        int cur = nums[0], n = nums.length;
        for (int i = 0; i < n; i++) {
            cur = Math.min(cur, nums[i]);
            if (cur == nums[i]) continue;
            for (int j = n - 1; j > i; j--) if (cur < nums[j] && nums[j] < nums[i]) return true;
        }
        return false;
    }
}

Python:

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        stack, cur = [], float('-inf')
        for i in range(len(nums) - 1, -1, -1):
            if nums[i] < cur:
                return True
            while stack and nums[i] > stack[-1]:
                cur = stack.pop()
            stack.append(nums[i])
        return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章