[leetcode] 334. Increasing Triplet Subsequence 解题报告

来源:互联网 发布:积分商城软件文档 编辑:程序博客网 时间:2024/06/11 17:15
class Solution {public:    bool increasingTriplet(vector<int>& nums) {    int c1 = INT_MAX, c2 = INT_MAX;    for (int x : nums) {        if (x <= c1) {            c1 = x;           // c1 is min seen so far (it's a candidate for 1st element)        } else if (x <= c2) { // here when x > c1, i.e. x might be either c2 or c3            c2 = x;           // x is better than the current c2, store it        } else {              // here when we have/had c1 < c2 already and x > c2            return true;      // the increasing subsequence of 3 elements exists        }    }    return false;}};

c1代表最小的数。c2代表(  (在它之前有一个比它小的数)的数  中的 最小的那个数)

用最长升序子序列(dp)做有些小题大做。

但这题可以拓展为"求是否存在升序子序列长度为3(或者k)"

只需要把代码改成


bool increasingTriplet(vector<int>& nums) {    int c1 = INT_MAX, c2 = INT_MAX;    for (int x : nums) {
if (x <= c1) {            c1 = x;           // c1 is min seen so far (it's a candidate for 1st element)        } else if (x <= c2) { // here when x > c1, i.e. x might be either c2 or c3            c2 = x;           // x is better than the current c2, store it        } else if (x <= c3){                        c3 = x;        }else{            return true;        }
} return false;}

多一个c3即可,其中c3的含义是"  (在此前有两个比它小的数)的数 中最小的那个数"

阅读全文
0 0