Advertisement
sweet1cris

Untitled

Jan 9th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. public class Solution {
  2.     public int longestIncreasingContinuousSubsequence(int[] A) {
  3.         if (A == null || A.length == 0) {
  4.             return 0;
  5.         }
  6.        
  7.         int n = A.length;
  8.         int answer = 1;
  9.        
  10.         // from left to right
  11.         int length = 1; // just A[0] itself
  12.         for (int i = 1; i < n; i++) {
  13.             if (A[i] > A[i - 1]) {
  14.                 length++;
  15.             } else {
  16.                 length = 1;
  17.             }
  18.             answer = Math.max(answer, length);
  19.         }
  20.        
  21.         // from right to left
  22.         length = 1;
  23.         for (int i = n - 2; i >= 0; i--) {
  24.             if (A[i] > A[i + 1]) {
  25.                 length++;
  26.             } else {
  27.                 length = 1;
  28.             }
  29.             answer = Math.max(answer, length);
  30.         }
  31.        
  32.         return answer;
  33.     }
  34. }
  35.  
  36. //  方法二
  37. public class Solution {
  38.     /**
  39.      * @param A an array of Integer
  40.      * @return  an integer
  41.      */
  42.    
  43.     int LIS(int[] A) {
  44.         int n = A.length;
  45.         int[] f = new int[n];
  46.         int i, res = 0;
  47.         for (i = 0; i < n; ++i) {
  48.             f[i] = 1;
  49.             if (i > 0 && A[i-1] < A[i]) {
  50.                 f[i] = f[i-1] + 1;
  51.             }
  52.             if (f[i] > res) {
  53.                 res = f[i];
  54.             }
  55.         }
  56.        
  57.         return res;
  58.     }
  59.      
  60.     public int longestIncreasingContinuousSubsequence(int[] A) {
  61.         int n = A.length;
  62.         int r1 = LIS(A);
  63.         int i = 0, j = n-1, t;
  64.         while (i < j) {
  65.             t = A[i];
  66.             A[i] = A[j];
  67.             A[j] = t;
  68.             ++i;
  69.             --j;
  70.         }
  71.        
  72.         int r2 = LIS(A);
  73.        
  74.         if (r1 > r2) {
  75.             return r1;
  76.         }
  77.         else {
  78.             return r2;
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement