File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
src/com/fghpdf/LongestIncreasingSubsequence Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .fghpdf .LongestIncreasingSubsequence ;
2
+
3
+ /**
4
+ * @author fghpdf
5
+ * @date 2019/12/26
6
+ * https://leetcode.com/problems/longest-increasing-subsequence/
7
+ * https://leetcode.com/problems/longest-increasing-subsequence/discuss/74824/JavaPython-Binary-search-O(nlogn)-time-with-explanation
8
+ * len = 1 : [4], [5], [6], [3] => tails[0] = 3
9
+ * len = 2 : [4, 5], [5, 6] => tails[1] = 5
10
+ * len = 3 : [4, 5, 6] => tails[2] = 6
11
+ * (1) if x is larger than all tails, append it, increase the size by 1
12
+ * (2) if tails[i-1] < x <= tails[i], update tails[i]
13
+ **/
14
+ public class Solution {
15
+ public int lengthOfLIS (int [] nums ) {
16
+ int [] tails = new int [nums .length ];
17
+ int size = 0 ;
18
+ for (int x : nums ) {
19
+ int i = 0 ;
20
+ int j = size ;
21
+ while (i != j ) {
22
+ int middle = (i + j ) / 2 ;
23
+ if (tails [middle ] < x ) {
24
+ i = middle + 1 ;
25
+ } else {
26
+ j = middle ;
27
+ }
28
+ }
29
+ tails [i ] = x ;
30
+ if (i == size ) {
31
+ size ++;
32
+ }
33
+ }
34
+ return size ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments