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

Solved after help.

ref: https://leetcode.com/problems/132-pattern/solutions/94071/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation/

We are going to search for a subsequence s1, s2, s3, that s1 < s3 < s2. s3 should be as large as possible if we could find a s2 that satisfies s2 > s3. So we could use a decreasing stack to store all the elements from right to left, if the current number is larger than the top element, then the element we pop from the stack is a candidate for s3.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

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:
        stack = []
        s3 = None
        for each_num in nums[::-1]:
            while stack and stack[-1] < each_num:
                if s3:
                    s3 = max(s3, stack.pop())
                else:
                    s3 = stack.pop()
            stack.append(each_num)
            if s3 and each_num < s3:
                return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值