LeetCode 456. 132 Pattern——LeetCode刷题记录

于是我要开始做俗之又俗的leetCode刷题记录了。

一方面是贡献给大家题目的解,另一方面是督促自己刷题,希望每天都有至少一篇刷题的记录。

题目基本上都是leetCode的medium或者hard题,easy题目看看就行。

今天先来一发水水的题目~

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

大致意思是给一个整数数列,问其中有没有这样的子序列:ai, aj, ak (i < j < k )并且 ai < ak < aj,有的话返回true,没有的话返回false。


一开始考虑的是,完全遍历每一个三元组,查看是否符合要求,但是这种方法显然时间复杂度为O(N3),而考虑到n是1万5的这个数量级,很容易就知道,时间复杂度太高了。

于是考虑到,并不需要遍历每一个三元组,只需要找到头尾两个值,看中间是否存在一个值大于头尾,并且尾值大于头值,这个过程直接通过遍历取max就可以得到。

于是时间复杂度被降低到了O(n2)。

代码如下:

public class Solution {
    public boolean find132pattern(int[] nums) {
        if(nums.length<3)
            return false;
        for(int i = 0;i<nums.length;i++){
            int max = Integer.MIN_VALUE;
            for(int j = i+1;j<nums.length;j++){
                if(max<nums[j]){
                    max = nums[j];
                }
                if(max>nums[j]&&max>nums[i]&&nums[i]<nums[j]){
                    return true;
                }
            }
        }
        return false;
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值