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;
    }
};
相关推荐
多喝开水少熬夜29 分钟前
Trie树相关算法题java实现
java·开发语言·算法
WBluuue43 分钟前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp1 小时前
牛客网华为在线编程题
算法
黑屋里的马3 小时前
java的设计模式之桥接模式(Bridge)
java·算法·桥接模式
sin_hielo3 小时前
leetcode 1611
算法·leetcode
李小白杂货铺3 小时前
识别和破除信息茧房
算法·信息茧房·识别信息茧房·破除信息茧房·算法推荐型茧房·观点过滤型茧房·茧房
来荔枝一大筐4 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
暴风鱼划水4 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
zl_vslam5 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
是苏浙5 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法