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

    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
        }
    }
  • 相关阅读:
    洛谷P1033 自由落体 题解
    尴尬
    UVA11988 【Broken Keyboard (a.k.a. Beiju Text)】:题解
    UVA101 The Blocks Problem 题解
    TCP的粘包和拆包问题及解决办法(C#)
    MIPS学习笔记(一)
    MySQL基础(一)
    博客园的标签怎么变了两下???
    nextInt()和nextLine()连用报错
    C++代码雨
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14068462.html
Copyright © 2011-2022 走看看