We first record two numbers, first and second, and then iterate over the nums vector. If the num is less than or equal to first, we reset first to it. If the num is greater than first but less than or equal to second, we reset second to it. When we find a number larger than both first and second, we know there is a triplet subsequence. This is because when second is set, it means we have found a number less than second. Consequently, when we find a number, called num, that is larger than second, we know there exists a triplet sequence: some number less than second -> second -> num.
impl Solution {
pub fn increasing_triplet(nums: Vec<i32>) -> bool {
let mut first = std::i32::MAX;
let mut second = first;
for &num in nums.iter() {
if num <= first {
first = num;
} else if num <= second {
second = num;
} else {
return true;
}
}
false
}
}
Practice Dates
Description
Link: https://leetcode.com/problems/increasing-triplet-subsequence/description/
Solution
We first record two numbers,
first
andsecond
, and then iterate over thenums
vector. If thenum
is less than or equal tofirst
, we resetfirst
to it. If thenum
is greater thanfirst
but less than or equal tosecond
, we resetsecond
to it. When we find a number larger than bothfirst
andsecond
, we know there is a triplet subsequence. This is because whensecond
is set, it means we have found a number less thansecond
. Consequently, when we find a number, callednum
, that is larger thansecond
, we know there exists a triplet sequence:some number less than second -> second -> num
.Performance
Time complexity: