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 arri < arrj < arrk 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 > numsi时,更新second=first, first=numsi。这样,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 小时前
技术白皮书:iRobotCAM如何解决机器人激光切割应用中的核心难点,从CAD离线编程到双目视觉定位与轨迹自适应提升复杂空间曲线切割的精度、效率与柔性化水平
人工智能·算法
ZhengEnCi4 小时前
大模型的分类到底怎么分:从基础模型到推理模型、从通用到专用的完整图谱
算法
取名真是5 小时前
Python 算法知识点从基础到进阶
开发语言·python·算法
罗西的思考5 小时前
【轻量化复刻大模型 / KIMI K3】KDA 模块交互式演示
人工智能·算法·机器学习
nm_zfyjt7 小时前
信息流广告投放优化实践:线索成本评估模型与转化链路重构(家装建材案例)
算法·重构·内蒙古朋友圈广告服务商·内蒙古朋友圈获客
w_zero_one8 小时前
算法--构造
java·数据结构·算法
其实防守也摸鱼9 小时前
信创安全竞赛知识总结与题库
大数据·网络·人工智能·算法·安全·php
小超人诞生日记10 小时前
C++ 智能指针的使用及其原理详解
c++·算法
AiNightVision13 小时前
无人机夜视模块如何选择?——从参数指标到系统集成的完整选型指南
人工智能·算法·计算机视觉·车载系统·无人机·视频·智能硬件