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 exists, return false
.
Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid.
Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists.
Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
Follow up: Could you implement a solution that runs in O(n)
time complexity and O(1)
space complexity?
# @param {Integer[]} nums
# @return {Boolean}
def increasing_triplet(nums)
min3 = [nil, nil, nil]
nums.each do |x|
if min3[1].nil?
min3[1] = x
elsif min3[2].nil? && x <= min3[1]
min3[1] = x
elsif min3[2].nil?
min3[2] = x
elsif x > min3[2]
return true
elsif x > min3[1]
min3[2] = x
elsif min3[0].nil? && x < min3[1]
min3[0] = x
elsif !min3[0].nil? && x > min3[0]
min3 = [nil, min3[0], x]
elsif !min3[0].nil? && x < min3[0]
min3[0] = x
end
end
false
end
impl Solution {
pub fn increasing_triplet(nums: Vec<i32>) -> bool {
let mut min3 = (None, None, None);
for x in nums {
match min3 {
(_, None, _) => min3.1 = Some(x),
(_, Some(b), None) if x < b => min3.1 = Some(x),
(_, Some(b), None) if x > b => min3.2 = Some(x),
(_, Some(b), Some(c)) if x > c => return true,
(_, Some(b), Some(c)) if x > b => min3.2 = Some(x),
(None, Some(b), Some(c)) if x < b => min3.0 = Some(x),
(Some(a), Some(b), Some(c)) if x > a => min3 = (None, Some(a), Some(x)),
(Some(a), Some(b), Some(c)) if x < a => min3.0 = Some(x),
_ => (),
}
}
false
}
}