前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Array - 334. Increasing Triplet Subsequence

Array - 334. Increasing Triplet Subsequence

作者头像
ppxai
发布2020-09-23 17:07:11
4070
发布2020-09-23 17:07:11
举报
文章被收录于专栏:皮皮星球皮皮星球

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.

**Note: **Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5] Output: true

思路:

这道题可以用动态规划来做,记录每一位为止的最长子序列的长度。时间复杂度和空间复杂度都是O(n), 当然也可以把空间复杂度优化成O(1),也就是只记录两位。但是这题我选择greedy来做。

代码:

代码语言:javascript
复制
class Solution {

    public boolean increasingTriplet(int[] nums) {
        if (nums == null || nums.length <= 2) return false;
        
        int min1 = Integer.MAX_VALUE;
        int min2 = Integer.MAX_VALUE;
        
        for (int num : nums) {
            if (num > min2) {
                return true;
            } else if (num < min1) {
                min1 = num;
            } else if (num > min1 && num < min2) {
                min2 = num;
            }
        }
        
        return false;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年06月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档