zoukankan      html  css  js  c++  java
  • LeetCode-334. Increasing Triplet Subsequence

    Description:

    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.

    Examples:
    Given [1, 2, 3, 4, 5],
    return true.

    Given [5, 4, 3, 2, 1],
    return false.

    题目大意是判断所给的数组中是否存在长度为3的递增序列。

    最常规的办法应该是两层循环,逐个判断。时间复杂度较高。还有一种比较巧妙的办法,维护两个距离最近的递增序列,如果能找到第三个则返回true。设置一个small,一个big,small<big。如果能找到一个不小于small和big的就返回true。时间复杂度为O(n)

    实现代码:

    public class Solution {
        public boolean increasingTriplet(int[] nums) {
            if(nums == null || nums.length < 3)
                return false;
            int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
            for(int value : nums) {
                if(value <= small)
                    small = value;
                else if(value <= big)
                    big = value;
                else
                    return true;
            }
            
            return false;
        }
    }
  • 相关阅读:
    docker 命令
    php cli命令
    windows 中docker连接使用mysql数据库
    什么是微服务
    PHP7新特性
    Docker Machine 命令
    关于Docker目录挂载的总结(二)
    实验十一 MySQLl备份与恢复1
    实验十--- MySQL过程式数据库对象
    实验九 存储函数和触发器
  • 原文地址:https://www.cnblogs.com/wxisme/p/5203814.html
Copyright © 2011-2022 走看看