Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
Example 1:
Input: [1, 2, 3, 4]
Output: False
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [3, 1, 4, 2]
Output: True
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: [-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].
代码
Approach 1: Brute Force
The simplest solution is to consider every triplet (i, j, k) and check if the corresponding numbers satisfy the 132 criteria. If any such triplet is found, we can return a True value. If no such triplet is found, we need to return a False value.
Complexity Analysis
Time complexity : O(n^3). Three loops are used to consider every possible triplet. Here, nn refers to the size of nums array.
Space complexity : O(1). Constant extra space is used.
classSolution {publicbooleanfind132pattern(int[] nums) {for (int i =0; i <nums.length-2; i++) {for (int j = i +1; j <nums.length-1; j++) {for (int k = j +1; k <nums.length; k++) {if (nums[k] > nums[i] && nums[j] > nums[k]) {returntrue; } } } }returnfalse; }}
Approach #2 Better Brute Force
Complexity Analysis
Time complexity : O(n^2). Two loops are used to find the nums[j],nums[k] pairs. Here, n refers to the size of nums array.
Space complexity : O(1). Constant extra space is used.