• 456. 132 Pattern


    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].

    题目含义:判断给定的数组中是否存在132模式的子串,例如例3描述的个数

    方法一:
     1     public boolean find132pattern(int[] nums) {
     2         if (nums.length < 3) return false;
     3         int n = nums.length,i=0,j,k;
     4         while (i<n)
     5         {
     6             while (i<n-2 && nums[i]>=nums[i+1]) i++;
     7             j=i+1;  //此时i比后面的一位小
     8             while (j<n-1 && nums[j]<=nums[j+1]) j++;
     9             k = j+1;//此时j比后面的一位大
    10 
    11             while (k<n)
    12             {
    13                 if (nums[k] >nums[i] && nums[k] <nums[j]) return true;  //找到的k比i大而且比j小 满足格式
    14                 k++;
    15             }
    16             i=j+1;
    17         }
    18         return false;
    19     }

    方法二:

     1     public boolean find132pattern(int[] nums) {
     2         if (nums.length < 3) return false;
     3         Stack<Integer> seconds = new Stack<>();
     4         Integer third = Integer.MIN_VALUE;
     5         for (int i = nums.length - 1; i >= 0; i--) {
     6             if (nums[i] < third) return true;
     7             else {
     8                 while (!seconds.isEmpty() && nums[i] > seconds.peek()) {
     9                     third = Math.max(third, seconds.pop()); //保证third永远是最大的,保证seconds中的值都大于等于nums[i]
    10                 }
    11             }
    12             seconds.push(nums[i]);
    13         }
    14         return false;        
    15     }


  • 相关阅读:
    WinForm中快捷键与组合按键的设置方法
    WinForm窗体间传值的方法
    System.Data.SqlClient 命名空间
    登录
    查找和替换
    进制转换
    对话框
    Object基类
    抽象类与抽象方法
    千位数减百位数不退位 区间代换
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7725990.html
Copyright © 2020-2023  润新知