国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Longest Increasing Subsequence

2019-11-09 18:57:18
字體:
來源:轉載
供稿:網友

Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

這道題目,常規解法O(n2)沒有難度,關鍵比較有意思的解題方式在于二分查找O(nlgn).

用一個數組tails,tails[i]的意思表示長度為i+1的LIS的末尾最小數。比如數組[2,3,5,4]長度為1的LIS最小的為2,那么tails[0]=2,長度為2的LIS有2,3和3,5末尾最小為3,所以tails[1]=3。以此類推有tails[2]=4。

反證可以確定,tails數組中的元素一定是有序遞增的。所以可以在tails數組中進行二分查找:從前往后遍歷輸入的數組,查找大于當前數n的最小數的位置:如果找到了,那么表明該長度的LIS最小末尾該被替換;如果沒有找到,則可以將n放置在原來最長LIS的后面組成一個長度加一的LIS。相當于動態生成了上面的tails數組。

代碼如下:

public class Solution { public int lengthOfLIS(int[] nums) { int[] tails = new int[nums.length]; int len = 0; for (int n : nums) { int l = 0,r = len; while (l != r) { int mid = (l + r) / 2; if (tails[mid] < n) l = mid + 1; else r = mid; } tails[l] = n; if (l == len) len ++; } return len; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双桥区| 临夏县| 晋江市| 介休市| 封开县| 勃利县| 子长县| 云龙县| 霸州市| 丰顺县| 图片| 黔江区| 嘉义市| 阜宁县| 宜黄县| 洪湖市| 马山县| 隆子县| 碌曲县| 蒲江县| 潜山县| 芮城县| 荔波县| 新野县| 斗六市| 东乡族自治县| 临泉县| 兴业县| 永登县| 高尔夫| 乌鲁木齐市| 界首市| 西盟| 曲阳县| 藁城市| 临沧市| 东乌| 新巴尔虎左旗| 仪征市| 四子王旗| 丹棱县|