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;
    }
};
相关推荐
随意起个昵称11 分钟前
【双指针】供暖器
算法
倒霉蛋小马14 分钟前
最小二乘法拟合直线,用线性回归法、梯度下降法实现
算法·最小二乘法·直线
codists37 分钟前
《算法导论(第4版)》阅读笔记:p82-p82
算法
埃菲尔铁塔_CV算法44 分钟前
深度学习驱动下的目标检测技术:原理、算法与应用创新
深度学习·算法·目标检测
float_com1 小时前
【背包dp-----分组背包】------(标准的分组背包【可以不装满的 最大价值】)
算法·动态规划
丶Darling.2 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
L_cl3 小时前
【Python 算法零基础 3.递推】
算法
int型码农3 小时前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树
先做个垃圾出来………4 小时前
汉明距离(Hamming Distance)
开发语言·python·算法
小羊在奋斗4 小时前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展