Leetcode 334. Increasing Triplet Subsequence
Given an integer array nums
, return true
if there exists a triple of indices (i, j, k)
such that i < j < k
and nums[i] < nums[j] < nums[k]
. If no such indices exist, return false
.
10^4
.false
.To solve this problem, we can utilize a linear scan approach with two auxiliary variables to keep track of the smallest and the second smallest elements encountered so far. This allows us to efficiently determine the presence of such an increasing triplet subsequence.
first
and second
with the maximum possible integer value.first
, update first
to the current element.second
, update second
to the current element.true
.false
.#include <vector>
#include <limits.h>
bool increasingTriplet(std::vector<int>& nums) {
int first = INT_MAX, second = INT_MAX;
for (int num : nums) {
if (num <= first) {
first = num;
} else if (num <= second) {
second = num;
} else {
return true;
}
}
return false;
}
The algorithm runs in O(n) time where n is the size of the input array, as it involves a single pass through the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?