[Java] 456. 132 mode---time complexity O(N^2)! ! !

Given a sequence of integers: a1, a2, …, an, a subsequence ai, aj, ak of 132 mode is defined as: when i <j <k, ai <ak <aj. Design an algorithm, when given a sequence of n numbers, verify whether the sequence contains a sub-sequence of 132 patterns.

Note: The value of n is less than 15000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no subsequence of 132 mode in the sequence.
Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a subsequence of 132 pattern in the sequence: [1, 4, 2].
Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are 3 subsequences of 132 pattern in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

代码:
public boolean find132pattern(int[] nums) {
    
    
		 if(nums.length<3) {
    
    
			 return false;
		 }
		 for(int i=1;i<nums.length-1;i++) {
    
    
			 int min=Integer.MAX_VALUE;
			 for(int j=0;j<i;j++) {
    
    
				 if(nums[j]<nums[i]&&min>nums[j]) {
    
    
					 min=nums[j];
				 }
			 }
			 if(min==Integer.MAX_VALUE) {
    
    
				 continue;
			 }
			 for(int j=i+1;j<nums.length;j++) {
    
    
				 if(nums[j]<nums[i]&&nums[j]>min) {
    
    
					 return true;
				 }
			 }
		 }
		 return false;
	 }
学习大佬代码:
public boolean find132pattern(int[] nums) {
    
    
        int n = nums.length;
        int last = Integer.MIN_VALUE; // 132中的2
        Stack<Integer> sta = new Stack<>();// 用来存储132中的3
        if(nums.length < 3)
            return false;
        for(int i=n-1; i>=0; i--){
    
    

            if(nums[i] < last) // 若出现132中的1则返回正确值
                return true;

            // 若当前值大于或等于2则更新2(2为栈中小于当前值的最大元素)
            while(!sta.isEmpty() && sta.peek() < nums[i]){
    
    
                last = sta.pop();
            }

            // 将当前值压入栈中
            sta.push(nums[i]);
        }
        return false;
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115159847