|
| 1 | +# 456. 132 Pattern |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Binary Search, Stack, Monotonic Stack, Ordered Set. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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]`. |
| 10 | + |
| 11 | +Return `true`** if there is a **132 pattern** in **`nums`**, otherwise, return **`false`**.** |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: nums = [1,2,3,4] |
| 18 | +Output: false |
| 19 | +Explanation: There is no 132 pattern in the sequence. |
| 20 | +``` |
| 21 | + |
| 22 | +Example 2: |
| 23 | + |
| 24 | +``` |
| 25 | +Input: nums = [3,1,4,2] |
| 26 | +Output: true |
| 27 | +Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. |
| 28 | +``` |
| 29 | + |
| 30 | +Example 3: |
| 31 | + |
| 32 | +``` |
| 33 | +Input: nums = [-1,3,2,0] |
| 34 | +Output: true |
| 35 | +Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. |
| 36 | +``` |
| 37 | + |
| 38 | + |
| 39 | +**Constraints:** |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +- `n == nums.length` |
| 44 | + |
| 45 | +- `1 <= n <= 2 * 105` |
| 46 | + |
| 47 | +- `-109 <= nums[i] <= 109` |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +## Solution |
| 52 | + |
| 53 | +```javascript |
| 54 | +/** |
| 55 | + * @param {number[]} nums |
| 56 | + * @return {boolean} |
| 57 | + */ |
| 58 | +var find132pattern = function(nums) { |
| 59 | + if (nums.length < 3) return false; |
| 60 | + var stack = []; |
| 61 | + var min = Array(nums.length); |
| 62 | + min[0] = nums[0]; |
| 63 | + for (var i = 1; i < nums.length; i++) { |
| 64 | + min[i] = Math.min(min[i - 1], nums[i]); |
| 65 | + } |
| 66 | + for (var j = nums.length - 1; j >= 0; j--) { |
| 67 | + if (nums[j] > min[j]) { |
| 68 | + while (stack.length && stack[stack.length - 1] <= min[j]) stack.pop(); |
| 69 | + if (stack.length && stack[stack.length - 1] < nums[j]) return true; |
| 70 | + stack.push(nums[j]); |
| 71 | + } |
| 72 | + } |
| 73 | + return false; |
| 74 | +}; |
| 75 | +``` |
| 76 | + |
| 77 | +**Explain:** |
| 78 | + |
| 79 | +nope. |
| 80 | + |
| 81 | +**Complexity:** |
| 82 | + |
| 83 | +* Time complexity : O(n). |
| 84 | +* Space complexity : O(n). |
0 commit comments