Advertisement
sweet1cris

Untitled

Jan 9th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums: The integer array
  4.      * @return: The length of LIS (longest increasing subsequence)
  5.      */
  6.    
  7.    
  8.     public int longestIncreasingSubsequence(int[] nums) {
  9.         int []f = new int[nums.length];
  10.         int max = 0;
  11.         for (int i = 0; i < nums.length; i++) {
  12.             f[i] = 1;
  13.             for (int j = 0; j < i; j++) {
  14.                 if (nums[j] < nums[i]) {
  15.                     f[i] = f[i] > f[j] + 1 ? f[i] : f[j] + 1;
  16.                 }
  17.             }
  18.             if (f[i] > max) {
  19.                 max = f[i];
  20.             }
  21.         }
  22.         return max;
  23.     }
  24. }
  25.  
  26.  
  27. // O(nlogn) Binary Search
  28. public class Solution {
  29.     /**
  30.      * @param nums: The integer array
  31.      * @return: The length of LIS (longest increasing subsequence)
  32.      */
  33.     public int longestIncreasingSubsequence(int[] nums) {
  34.         int[] minLast = new int[nums.length + 1];
  35.         minLast[0] = Integer.MIN_VALUE;
  36.         for (int i = 1; i <= nums.length; i++) {
  37.             minLast[i] = Integer.MAX_VALUE;
  38.         }
  39.        
  40.         for (int i = 0; i < nums.length; i++) {
  41.             // find the first number in minLast >= nums[i]
  42.             int index = binarySearch(minLast, nums[i]);
  43.             minLast[index] = nums[i];
  44.         }
  45.        
  46.         for (int i = nums.length; i >= 1; i--) {
  47.             if (minLast[i] != Integer.MAX_VALUE) {
  48.                 return i;
  49.             }
  50.         }
  51.        
  52.         return 0;
  53.     }
  54.    
  55.     // find the first number > num
  56.     private int binarySearch(int[] minLast, int num) {
  57.         int start = 0, end = minLast.length - 1;
  58.         while (start + 1 < end) {
  59.             int mid = (end - start) / 2 + start;
  60.             if (minLast[mid] < num) {
  61.                 start = mid;
  62.             } else {
  63.                 end = mid;
  64.             }
  65.         }
  66.        
  67.         return end;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement