zoukankan      html  css  js  c++  java
  • LeetCode——Increasing Triplet Subsequence

    Question

    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.

    Solution

    数学逻辑。

    Code

    class Solution {
    public:
        bool increasingTriplet(vector<int>& nums) {
            int c1 = INT_MAX, c2 = INT_MAX;
            for (int i : nums) {
                if (i <= c1)        // 当前最小的数
                    c1 = i;
                else if (i <= c2)   // 第二或者第三大的数
                    c2 = i;
                else     // 如果存在一个比当前最小的大,且比第二大的数大(能够成为第二大,说明它之前有比它小的),那么这个数前面肯定有两个比它小的
                    return true;
            }
            return false;
            
        }
    };
    
  • 相关阅读:
    设计模式之策略模式
    assert断言——调试中不应该是syso
    Spring AOP
    MyBatis
    事务处理与使用连接池管理连接
    管理结果集(ResultSet)
    执行SQL语句的方式
    JDBC基础:
    NIO.2
    NIO
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7624365.html
Copyright © 2011-2022 走看看