LintCode 1287 · Increasing Triplet Subsequence (贪心算法)

1287 · Increasing Triplet Subsequence

Algorithms

Medium

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.

Example

Example1

Input: [1, 2, 3, 4, 5]

Output: true

Example2

Input: [5, 4, 3, 2, 1]

Output: false

解法1:参考的网上的答案。first和second分别表示当前所遇到的一小一大数的比较小的组合。如果碰到一个新数>second,就可以直接返回true。如果first<新数<=second,那么更新second,first不用更新。如果新数<=first,那么更新first=新数。

cpp 复制代码
class Solution {
public:
    /**
     * @param nums: a list of integers
     * @return: return a boolean
     */
    bool increasingTriplet(vector<int> &nums) {
        int n = nums.size();
        if (n < 3) return false;
        int first = nums[0], second = INT_MAX;
        for (int i = 1; i < n; i++) {
            if (second < nums[i]) {
                return true;
            } else if (first < nums[i]) {
                second = nums[i];
            } else {
                first = nums[i];
            }
        }
        return false;
    }
};

也可以当first > nums[i]时,更新second=first, first=nums[i]。这样,first, second组合就是尽可能小的一小一大组合了。

cpp 复制代码
class Solution {
public:
    /**
     * @param nums: a list of integers
     * @return: return a boolean
     */
    bool increasingTriplet(vector<int> &nums) {
        int n = nums.size();
        if (n < 3) return false;
        int first = nums[0], second = INT_MAX;
        for (int i = 1; i < n; i++) {
            if (second < nums[i]) {
                return true;
            } else if (first < nums[i]) {
                second = nums[i];
            } else if (first > nums[i]) {
                second = first;
                first = nums[i];
            }
        }
        return false;
    }
};
相关推荐
哎嗨人生公众号9 分钟前
手写求导公式,让轨迹优化性能飞升,150ms变成9ms
开发语言·c++·算法·机器人·自动驾驶
foundbug99913 分钟前
STM32 内部温度传感器测量程序(标准库函数版)
stm32·单片机·嵌入式硬件·算法
Hello.Reader13 分钟前
为什么学线性代数(一)
线性代数·算法·机器学习
_深海凉_20 分钟前
LeetCode热题100-找到字符串中所有字母异位词
算法·leetcode·职场和发展
木井巳24 分钟前
【递归算法】目标和
java·算法·leetcode·决策树·深度优先
旖-旎31 分钟前
哈希表(字母异位次分组)(5)
数据结构·c++·算法·leetcode·哈希算法·散列表
别或许37 分钟前
4、高数----一元函数微分学的计算
人工智能·算法·机器学习
_深海凉_43 分钟前
LeetCode热题100-最长连续序列
算法·leetcode·职场和发展
这里没有酒1 小时前
[信息安全] AES128 加密/解密 --> state 矩阵
算法
无限进步_1 小时前
【C++】多重继承中的虚表布局分析:D类对象为何有两个虚表?
开发语言·c++·ide·windows·git·算法·visual studio