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;
    }
};
相关推荐
wearegogog1231 小时前
光谱分析波段选择的连续投影算法
算法
执笔论英雄1 小时前
【RL】DAPO 数据处理
算法
why1512 小时前
面经整理——算法
java·数据结构·算法
悦悦子a啊2 小时前
将学生管理系统改造为C/S模式 - 开发过程报告
java·开发语言·算法
痕忆丶2 小时前
双线性插值缩放算法详解
算法
_codemonster3 小时前
深度学习实战(基于pytroch)系列(四十八)AdaGrad优化算法
人工智能·深度学习·算法
鹿角片ljp4 小时前
力扣140.快慢指针法求解链表倒数第K个节点
算法·leetcode·链表
自由生长20244 小时前
位运算第1篇-异或运算-快速找出重复数字
算法
xxxxxmy4 小时前
同向双指针(滑动窗口)
python·算法·滑动窗口·同向双指针
释怀°Believe4 小时前
Daily算法刷题【面试经典150题-5️⃣图】
算法·面试·深度优先