xiutianxiudi

Leetcode 300. Longest Increasing Subsequence

Sep 22nd, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. class Solution {
  2.  
  3.     // T: O(n*log(n)), S: O(n)
  4.     public int lengthOfLIS(int[] nums) {
  5.         if(nums == null) {
  6.             return 0;
  7.         }
  8.  
  9.         int n = nums.length;
  10.  
  11.         // maxSize: lengthOfLIS(Arrays.copyOfRange(nums, 0, i + 1))
  12.         int maxSize = 0;
  13.  
  14.         int[] f = new int[n];
  15.         Arrays.fill(f, Integer.MAX_VALUE);
  16.  
  17.         for(int i = 0; i < n; i++) {
  18.             int insertIndex = binarySearch(f, 0, maxSize - 1, nums[i]);
  19.  
  20.             f[insertIndex] = Math.min(f[insertIndex], nums[i]);
  21.             maxSize = Math.max(maxSize, insertIndex + 1);
  22.         }
  23.         return maxSize;
  24.     }
  25.  
  26.     // return the smallest index i s.t. nums[i] >= target,
  27.     // return endIndex + 1 if such index doesn't exists
  28.     private int binarySearch(int[] nums, int startIndex, int endIndex, int target) {
  29.         int li = startIndex;
  30.         int hi = endIndex;
  31.         while(li <= hi) {
  32.             int mi = li + (hi - li)/2;
  33.             if(nums[mi] >= target) {
  34.                 if(mi == li || nums[mi - 1] < target) {
  35.                     return mi;
  36.                 }
  37.                 hi = mi - 1;
  38.             } else {
  39.                 li = mi + 1;
  40.             }
  41.         }
  42.         return endIndex + 1;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment