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
    }
}
复制代码

 

posted @   johnny_zhao  阅读(76)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示