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;
    }
};
相关推荐
仰泳的熊猫1 小时前
LeetCode:538. 把二叉搜索树转换为累加树/1038. 从二叉搜索树到更大和树
数据结构·c++·算法·leetcode
weixin_307779131 小时前
Clickhouse导出库的表、视图、用户和角色定义的SQL语句
开发语言·数据库·算法·clickhouse·自动化
piggy侠1 小时前
【GitHub每日速递 251016】23k star,Daytona:90ms内极速运行AI代码,安全弹性基础设施来袭!
算法·github
小龙报2 小时前
《算法通关指南---C++编程篇(1)》
开发语言·c++·程序人生·算法·学习方法·visual studio
Cx330❀2 小时前
《C++ 手搓list容器底层》:从结构原理深度解析到功能实现(附源码版)
开发语言·数据结构·c++·经验分享·算法·list
Swift社区2 小时前
LeetCode 399 除法求值
算法·leetcode·职场和发展
仰泳的熊猫2 小时前
LeetCode:98. 验证二叉搜索树
数据结构·c++·算法·leetcode
Python智慧行囊2 小时前
图像处理(三)--开运算与闭运算,梯度运算,礼帽与黑帽
人工智能·算法·计算机视觉
前端小L2 小时前
动态规划的“细节魔鬼”:子序列 vs 子数组 —— 最长重复子数组
算法·动态规划
草莓熊Lotso2 小时前
《算法闯关指南:优选算法--二分查找》--19.x的平方根,20.搜索插入位置
java·开发语言·c++·算法