a stack solution (C++, easy to understand)


  • 0
    G

    This solution uses a stack to keep an strictly increasing sequence. The stack here contains 2 elements at most. Easy to understand.

    bool increasingTriplet(vector<int>& nums) {
        if (nums.size() < 3) {
            return false;
        }
        
        stack<int> s;
        int bar = INT_MAX;
        for (auto num : nums) {
            if (num > bar) {
                return true;
            }
            
            while (!s.empty() && num <= s.top()) {
                s.pop();
            }
            
            if (!s.empty()) {
                bar = min(bar, num);
            }
            
            s.push(num);
            
        }
        
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.