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;
            
        }
    };
    
  • 相关阅读:
    软件需求分析
    行高line-height 和vertical-align
    python中的集合基础知识
    python中字典常用的函数和用法
    python中字符串常用的函数
    day-75CRM
    day-74CRM
    day73CRM
    day-72Django源码解析
    day-71Django补充
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7624365.html
Copyright © 2011-2022 走看看