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;
            
        }
    };
    
  • 相关阅读:
    《PHP
    2018/06/11 数据库设计规范
    RequireJs 与 SeaJs的相同之处与区别
    null 与 undefinded
    page 分页
    fullPage的使用
    touch事件(寻找触摸点 e.changedTouches)
    t添加最佳视口
    随鼠标动的炫彩小球
    随机小球
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7624365.html
Copyright © 2011-2022 走看看