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
        }
    }
  • 相关阅读:
    mysql TO_DAYS()函数
    MySQL year函数
    protobuff java 包编译(Windows)
    苹果笔记本只有电源键能用的解决办法
    linux普通用户获取管理员权限
    linux用户管理
    基于ASIHTTPRequest封装的HttpClient
    Object-C 多线程中锁的使用-NSLock
    appstore 上传需要的icon
    iPhone之IOS5内存管理(ARC技术概述)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14068462.html
Copyright © 2011-2022 走看看