The O(N) Increasing Triplet Subsequence Algorithm

  • 时间:2020-09-24 11:41:27
  • 分类:网络文摘
  • 阅读:104 次

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.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:

Input: [5,4,3,2,1]
Output: false

Checking Increasing Triplet Subsequence in O(N) Algorithm

The most intutive solution will be to bruteforce a triplet in O(N^3) and see if it is in increasing order. Obviously, this is inefficient. A Better solution is to record the smaller numbers as iterating the array.

This greedy approach works, as we are iterating the array from left to the right. If we find out a number that is different than the two numbers we have found – and both numbers are smaller than the current number, we know it has a increasing triplet subsequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int first = INT_MAX, second = INT_MAX;
        for (const auto &n: nums) {
            if (n <= first) {
                first = n;
            } else if (n <= second) {
                second = n;
            } else return true;
        }
        return false; // can't find such triplet increasing subsequence
    }
};
class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int first = INT_MAX, second = INT_MAX;
        for (const auto &n: nums) {
            if (n <= first) {
                first = n;
            } else if (n <= second) {
                second = n;
            } else return true;
        }
        return false; // can't find such triplet increasing subsequence
    }
};

I have to say, this trick is elegant and makes the algorithm efficient in O(N) time and O(1) constant space.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
数学题:在1989后面写下一串数字  数学题:三一班图书角中的故事书本数比连环画本数的2倍多8本  数学题:兔妈妈拔回家一筐萝卜  奥数题:两次相遇地点间相距120千米  数学题:甲乙两仓库共有棉花2600包  百度快照投诉功能恢复正常,新增快照失效类型选项  新网站排名不稳固,三大SEO优化技巧你做到了吗?  SEO优化网站诊断的几个技巧,你知道多少?  bootstrap响应式导航激活高亮,dedecms导航代码分享  为什么自媒体比SEO更火?答案都在这里 
评论列表
添加评论