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=新数。

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组合就是尽可能小的一小一大组合了。

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. LintCode 1287 · Increasing Triplet Subsequence (贪心算法)

    2023-12-09 16:40:07       39 阅读
  2. 贪心算法

    2023-12-09 16:40:07       21 阅读
  3. 贪心算法

    2023-12-09 16:40:07       10 阅读
  4. 计算机算法贪心算法

    2023-12-09 16:40:07       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-09 16:40:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-09 16:40:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-09 16:40:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-09 16:40:07       18 阅读

热门阅读

  1. codeforces每日两道思维题(第 四 天)

    2023-12-09 16:40:07       43 阅读
  2. Matlab 镜像变换(2D)

    2023-12-09 16:40:07       36 阅读
  3. 源码安装git

    2023-12-09 16:40:07       37 阅读
  4. 查看域名A记录

    2023-12-09 16:40:07       27 阅读
  5. ogre3d 资料

    2023-12-09 16:40:07       38 阅读
  6. Flink 读写 HBase 总结

    2023-12-09 16:40:07       39 阅读
  7. Docker 常用命令

    2023-12-09 16:40:07       46 阅读