leetcode - 456. 132 Pattern

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.

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 <= 2 * 10^5
-10^9 <= nums[i] <= 10^9

Solution

Didn’t even come up with n 2 n^2 n2 solution, I feel so bad.

o ( n 2 ) o(n^2) o(n2) solution

Scan from left to right, keep track of the minimum value, and at each point scan the right of the list, to find the middle element.

Time complexity: o ( n 2 ) o(n^2) o(n2)
Space complexity: o ( 1 ) o(1) o(1)

Monotonic Stack

ref: https://leetcode.com/problems/132-pattern/solutions/906876/python-o-n-solution-with-decreasing-stack-explained/?envType=daily-question&envId=2023-09-30

Code

o ( n 2 ) o(n^2) o(n2) solution

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        min_val = nums[0]
        for j in range(1, len(nums)):
            if nums[j] <= min_val:
                min_val = nums[j]
                continue
            else:
                for k in range(j + 1, len(nums)):
                    if min_val < nums[k] < nums[j]:
                        return True
        return False

Monotonic Stack

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        min_vals = []
        min_val = 1000000001
        for i, each_num in enumerate(nums):
            min_vals.append(min_val)
            min_val = min(min_val, each_num)
        stack = []
        for i in range(len(nums) - 1, -1, -1):
            if nums[i] < min_vals[i]:
                continue
            while stack and stack[-1] <= min_vals[i]:
                stack.pop()
            if stack and stack[-1] < nums[i]:
                return True
            stack.append(nums[i])
        return False

你可能感兴趣的:(OJ题目记录,leetcode,算法,数据结构)