Middle-题目44:334. Increasing Triplet Subsequence

题目原文:
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
题目大意:
给出一个数组,判断是否存在一个递增的长度为3的子序列。
题目分析:
(1) 朴素解法: O(n3) 暴力搜索;
(2) 最长递增子列:引用Middle-题目33的方法判断最长递增子列的长度是否>=3,最好的时间复杂度是O(nlogn)。
(3) O(n)算法:扫描一遍数组,令a1是当前最小值,a2是a1以后次小值,则如果当前的数比a2还大,就存在。
源码:(language:java)

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int a1 = Integer.MAX_VALUE,a2 = Integer.MAX_VALUE;
        for(int num : nums) {
            if(num<=a1) 
                a1=num;
            else if(num<=a2)
                a2=num;
            else
                return true;
        }
        return false;
    }
}

成绩:
1ms,beats 34.32%,众数1ms,65.68%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值