문제
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 * 105
-10^9 <= nums[i] <= 109
풀이
투포인터로 적근했다
근데 비효율적이다.
답안
/**
* @param {number[]} nums
* @return {boolean}
*/
var find132pattern = function (nums) {
const n = nums.length;
if (n < 3) return false;
let third = -Infinity; // nums[k]를 추적 (3에 해당)
let stack = []; // 스택을 사용해 잠재적인 nums[j] 값을 추적 (2에 해당)
// 배열을 뒤에서부터 탐색
for (let i = n - 1; i >= 0; i--) {
if (nums[i] < third) {
return true;
}
while (stack.length > 0 && nums[i] > stack[stack.length - 1]) {
third = stack.pop();
}
stack.push(nums[i]);
}
return false;
};
'JavaScript > Leetcode' 카테고리의 다른 글
N-Queens II (1) | 2024.10.24 |
---|---|
Generate Parentheses (Medium) (0) | 2024.10.23 |
Trapping Rain Water (Hard) (5) | 2024.10.23 |
Group Anagrams (Medium) (1) | 2024.09.28 |
Container With Most Water (Medium) (0) | 2024.09.27 |