package LeetCode_456 import java.util.* /** * 456. 132 Pattern * https://leetcode.com/problems/132-pattern/ * 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 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: 1. n == nums.length 2. 1 <= n <= 104 3. -109 <= nums[i] <= 109 * */ class Solution { /* solution 1: bruce force, Time:O(n^2), Space:O(1) * */ fun find132pattern(nums: IntArray): Boolean { if (nums == null || nums.isEmpty()) { return false } val n = nums.size //solution 1 var min = Int.MAX_VALUE for (j in nums.indices) { //min is nums[i] min = Math.min(min, nums[j]) //because i<j<k, so scan from right to current j //nums[i] < nums[k] < nums[j] for (k in n - 1 downTo j) { if (min < nums[k] && nums[k] < nums[j]) { return true } } } return false } }