Given an unsorted array, determine whether there is an increasing subsequence of length 3 in this array.
The mathematical expression is as follows:
If there is such an i, j, k, and satisfies 0 ≤i <j <k < n-1,Make arr[i] < arr[j] < arr[k], return true; otherwise, return false.
Note: the time complexity and space complexity of the algorithm are required to be O(n) and O(1).
Example 1:
Input: [1,2,3,4,5] Output: true
Thinking: two ways of thinking
Idea 1: use d[i] array to save the length of discontinuous increasing sequence ending with I, max to save the maximum value of element, imax to be the index position of maximum value, min to save the minimum value of element, and imin to be the index position of minimum value.
There are several situations,
If nums[i] is greater than nums[i-1] and greater than max, then d [i] = max (d [I-1], d [IMAX] + 1;
If nums[i] is greater than nums[i-1] and greater than min is less than max, then d[i]=max(d[i-1],d[imin])+1;
If nums[i] is less than nums[i-1] and more than min is less than max, then d[i]=d[imin]+1;
If the last nums[i] is less than min, then d[i]=1, that is, its own length;
class Solution { //Discontinuous increment public boolean increasingTriplet(int[] nums) { if(nums.length<3){return false;} int max=nums[0];int imax=0; int min=nums[0];int imin=0; int[] d = new int[nums.length];//The length of the longest discontinuous increasing sequence ending with i d[0]=1; int count=0; for(int i=1;i<nums.length;i++){ if(nums[i]>nums[i-1]&&nums[i]>max){ d[i]=Math.max(d[i-1],d[imax])+1; }else if(nums[i]>nums[i-1]&&nums[i]>min){ d[i]=Math.max(d[i-1],d[imin])+1; }else if(nums[i]>min){ d[i]=d[imin]+1; }else{ d[i]=1; } //If the length reaches 3, it is satisfied if(d[i]==3){ return true; } if(max<nums[i]){ max=nums[i]; imax=i; } if(min>nums[i]){ min=nums[i]; imin=i; } } return false; } }
Idea 2: use num1 and num2. Ensure that num1 is less than nums2, and if the number traversed is greater than nums2, it will meet the requirement of three number increments. Return to true
class Solution { public boolean increasingTriplet(int[] nums) { int num1 = Integer.MAX_VALUE; int num2 = Integer.MAX_VALUE; for(int num : nums){ if(num <= num1){ num1 = num; }else if(num > num1 && num <=num2){ num2 = num; }else{ return true; } } return false; } }