码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:longest-increasing

时间:2016-03-18 17:33:02      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

1、

Give an integer array,find the longest increasing continuous subsequence in this array.

An increasing continuous subsequence:

  • Can be from right to left or from left to right.
  • Indices of the integers in the subsequence should be continuous.

For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.

For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.

2、思路:

  1、从左到右判断

  2、从右到左判断

  3、初始化为一个参数为1,进行逐一判断

3、

  

public class Solution {
    public int longestIncreasingContinuousSubsequence(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int n = A.length;
        int answer = 1;
        
        // from left to right
        int length = 1; // just A[0] itself
        for (int i = 1; i < n; i++) {
            if (A[i] > A[i - 1]) {
                length++;
            } else {
                length = 1;
            }
            answer = Math.max(answer, length);
        }
        
        // from right to left
        length = 1;
        for (int i = n - 2; i >= 0; i--) {
            if (A[i] > A[i + 1]) {
                length++;
            } else {
                length = 1;
            }
            answer = Math.max(answer, length);
        }
        
        return answer;
    }
}
//暂无搞懂
// version 2: Memorization Search, can not get accepted, just show you how to write a memorization search code
public class Solution {
    private int[] flag;
    private int[] dp;
    private int[] A;
    private int n;
    
    public static int VISITED = 1;
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        if (A == null) {
            return 0;
        }
        
        // initialize
        n = A.length;
        flag = new int[n];
        dp = new int[n];
        this.A = A;

        // memorization search
        int ans = 0;
        for (int i = 0; i < n; i++) {
            dp[i] = dfs(i);
            ans = Math.max(ans, dp[i]);
        }
        
        return ans;
    }
    
    int dfs(int index)   {
        if (flag[index] == VISITED) {
            return dp[index];
        }
        
        int ans = 1;
        if (index - 1 >= 0 && A[index] < A[index - 1]) {
            ans = dfs(index - 1) + 1;
        } 
        if (index + 1 < n && A[index] < A[index + 1]) {
            ans = Math.max(ans,  dfs(index + 1) + 1);
        }
        flag[index] = VISITED;
        dp[index] = ans;
        return ans;
    }
}

 

leetcode:longest-increasing

标签:

原文地址:http://www.cnblogs.com/zilanghuo/p/5292889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!