leetcode (Longest Continuous Increasing Subsequence)
阿新 • • 發佈:2018-12-01
Title:Longest Continuous Increasing Subsequence 674
Difficulty:Easy
原題leetcode地址:https://leetcode.com/problems/longest-continuous-increasing-subsequence/
1. 後面的數大每次加加,否則為1,每次都比較下大小
時間複雜度:O(n),一次一層for迴圈,需要遍歷整個陣列。
空間複雜度:O(1),沒有申請額外的空間。
/** * 後面的數大每次加加,否則為1,每次都比較下大小 * @param nums * @return */ public static int findLengthOfLCIS(int[] nums) { if (nums == null || nums.length <= 0) { return 0; } if (nums.length == 1) { return 1; } int count = 1; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length - 1; i++) { if (nums[i + 1] > nums[i]) { count++; } else { count = 1; } if (count > max) { max = count; } } return max; }
2. 動態規劃
時間複雜度:O(n),一次一層for迴圈,需要遍歷整個陣列。
空間複雜度:O(n),申請與nums長度一樣的大的陣列長度n。
/** * 動態規劃 * @param nums * @return */ public static int findLengthOfLCIS1(int[] nums) { if (nums == null || nums.length <= 0) { return 0; } if (nums.length == 1) { return 1; } int tmp[] = new int[nums.length]; tmp[0] = 1; for (int i = 1; i < nums.length; i++) { tmp[i] = 1; if (nums[i] > nums[i - 1]) { tmp[i] = tmp[i - 1] + 1; } } int max = Integer.MIN_VALUE; for (int i = 0; i < tmp.length; i++) { if (tmp[i] > max) { max = tmp[i]; } } return max; }