leetcode:longest-increasing
Posted 自朗活
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode:longest-increasing相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章