Problem Description
Explanation:
To solve this problem in O(n) time complexity and O(1) space complexity, we can use a two-pointer approach. We maintain two variables, first
and second
, to keep track of the smallest and second smallest elements found so far. We iterate through the array and update these variables accordingly. If we encounter a number greater than both first
and second
, we have found a triplet and return true. If not, we keep updating first
and second
. If we finish iterating through the array without finding a triplet, we return false.
- Time complexity: O(n) where n is the number of elements in the array.
- Space complexity: O(1)
:
Solutions
class Solution {
public boolean increasingTriplet(int[] nums) {
if(nums == null || nums.length < 3) {
return false;
}
int first = Integer.MAX_VALUE;
int second = Integer.MAX_VALUE;
for(int num : nums) {
if(num <= first) {
first = num;
} else if(num <= second) {
second = num;
} else {
return true;
}
}
return false;
}
}
Related LeetCode Problems
Loading editor...