longest increasing subsequence
Find the length of the longest increasing subsequence in a given array
(subsequence, can be discontinuous subarray, needs to be continuous)
Eg: arr={2,1,6,4,5,2,7,4} The longest increasing subsequence is {2,4,5,7} and the length is 4
Solution one O(n 2 )
Ideas:
- Generate an auxiliary array temp, temp[i] represents the maximum subsequence length in the case of ending with arr[i]
- When setting temp[i], compare arr[i], traverse all the numbers in front that are smaller than arr[i], and add one to the maximum temp value of its set
shortcoming:
In idea (2), it is necessary to traverse all the numbers in front of the arr array that are smaller than arr[i], which is O(n), and the whole is O(n 2 )
Code:
public int[] maxSize() { int[] arr={2,1,6,4,5,2,7,4}; int[] temp=new int[arr.length]; temp[0]=1; int max; for(int i=1;i<arr.length;i++){ max=0; for(int j=0;j<i;j++){ if(arr[j]<arr[i]&&max<=temp[j]) max=temp[j]; } temp[i]=max+1; } return temp; }
Solution two O(nlogn)
It is an improvement on the idea (2) of solution 1, and the complexity is reduced by using the dichotomy method
Ideas:
- Temp has the concept of an effective area, that is, data can only be stored in a certain interval
- Temp[i] refers to the minimum end value of the longest subsequence of length i+1 in the valid area
The concept of Temp array is different from that in Solution 1 (it is more difficult to understand here)
For example: temp[1]=6 means that the minimum end value of the longest subsequence with length 1+1=2 is 6. At this time, if you continue to traverse arr, it is found that there is a subsequence of length 2 but the end value is less than 6 will replace (2, 1, 6, 2 1, 6->1, 2), the meaning of this is to always keep the value of the temp array at a minimum for subsequent increases
Arr : 2 1 5 7 3 2->1->1,5->1,5,7->1,3,7
1,5,7->1,3,7 means traversing so far, the subsequence of length 2 can end with 5 or 3, but in order to count the subsequent maximum value, replace the subsequence with the end of 3 sequence, adding
Note: The previous statistics will not be affected at this time. The length of the longest subsequence at the end of 1,5,7->1,3,7,7 is still 3 (the subsequence is 1,5,7),
The following number is 2 1,3,7->1,2,7 The minimum end of a subsequence of length 2 is 2 1,2
The following numbers are 9 1,2,7->1,2,7,9 The minimum end of the subsequence of length 4 is 9 1,5,7,9 (this is understood clearly)
Code:
// arr>temp, then arr<temp, replace public int [] maxSizeTwo() { int[] arr={2,1,6,4,5,2,7,4}; int[] temp = new int[arr.length]; int left=0,right=0,count=0,mid; temp[0]=arr[0]; for(int i=1;i<arr.length;i++){ right=count; while(left<right){ mid=(right+left)/2; if(arr[i]<temp[mid]){ right=mid-1; } else left=mid+1; } if(temp[left]<arr[i]){ count++; temp[left+1]=arr[i]; } else temp[left]=arr[i]; } return temp; }