LeetCode(334):递增的三元子序列 Increasing Triplet Subsequence(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2019.9.28

github:https://github.com/ChopinXBP/LeetCode-Babel

#程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

注意子序列和子串的区别。

min表示当前遇到的最小值,mid表示当前遇到的较小值。不断迭代替换,最终序列不一定是上升子序列,当一定能够证明满足条件。


传送门:递增的三元子序列

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.

给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。

数学表达式如下:

如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1,
使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。

说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。

示例 1:

输入: [1,2,3,4,5]
输出: true
示例 2:

输入: [5,4,3,2,1]
输出: false


/**
 *
 * 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.
 * 给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。
 * 数学表达式如下:
 * 如果存在这样的 i, j, k,  且满足 0 ≤ i < j < k ≤ n-1,
 * 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
 * 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。
 *
 */

public class IncreasingTripletSubsequence {
    public boolean increasingTriplet(int[] nums) {
        if(nums.length < 3){
            return false;
        }
        //min表示当前遇到的最小值,mid表示当前遇到的较小值
        //不断迭代替换,最终序列不一定是上升子序列,当一定能够证明满足条件
        int min = Integer.MAX_VALUE;
        int mid = Integer.MAX_VALUE;
        for(int num : nums){
            if(num <= min){
                min = num;
            }else if(num <= mid){
                mid = num;
            }else{
                return true;
            }
        }
        return false;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值