zoukankan      html  css  js  c++  java
  • LeetCode 456. 132 Pattern

    原题链接在这里:https://leetcode.com/problems/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].

    题解:

    We want to find out s1 < s3 < s2, actually we want to find out if there is a third value, s3 existing.

    We could use stack to store increasing value from right -> left. When we see bigger value, we pop and assign to s3.

    If we see a num < s3, we find such a value. Since s3 is initialized as Integer.MIN_VALUE. If we find num < s3, then s3 is updated from stack pop before.

    Time Comlexity: O(n). n = nums.length.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public boolean find132pattern(int[] nums) {
     3         if(nums == null || nums.length < 3){
     4             return false;
     5         }
     6         
     7         int s3 = Integer.MIN_VALUE;
     8         Stack<Integer> stk = new Stack<>();
     9         for(int i = nums.length - 1; i >= 0; i--){
    10             if(nums[i] < s3){
    11                 return true;
    12             }
    13             
    14             while(!stk.isEmpty() && stk.peek() < nums[i]){
    15                 s3 = stk.pop();
    16             }
    17             
    18             stk.push(nums[i]);
    19         }
    20         
    21         return false;
    22     }
    23 }
  • 相关阅读:
    ES数据-MySql处理Date类型的数据导入处理
    es搜索引擎
    Java Web学习路线
    九樱天下-观察期
    一些平常的总结
    ES搜索引擎-简单入门
    工作中异常的一些总结
    抽象和封装的一点总结
    python之路_django分页及session介绍
    python之路_django中母板及cookie介绍
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6592645.html
Copyright © 2011-2022 走看看