1. Description
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
2. Example
Given [1, 2, 3, 4, 5],
return true.
Given [5, 4, 3, 2, 1],
return false.
3. Code
public class LeetCode0334 {
public boolean increasingTriplet(int[] nums) {
if(nums == null || nums.length < 3){
return false;
}
int x = Integer.MAX_VALUE;
int y = Integer.MAX_VALUE;
for(int i =0; i< nums.length;i++){
if(x >= nums[i]){
x = nums[i];
}else if(y >= nums[i]){
y = nums[i];
}else{
return true;
}
}
return false;
}
public static void main(String[] args) {
LeetCode0334 leetcode = new LeetCode0334();
int[] nums = new int[]{5, 4, 3, 2, 1};
System.out.println(leetcode.increasingTriplet(nums));
}
}
Comments | NOTHING