国产探花免费观看_亚洲丰满少妇自慰呻吟_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; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜良县| 营口市| 大城县| 岱山县| 尖扎县| 阿合奇县| 湄潭县| 遂川县| 衡阳市| 广平县| 武强县| 舞钢市| 苍梧县| 海阳市| 婺源县| 驻马店市| 兴化市| 中宁县| 巴楚县| 巴彦淖尔市| 定远县| 镇赉县| 达州市| 藁城市| 宣城市| 登封市| 弥勒县| 西贡区| 岗巴县| 外汇| 高平市| 焉耆| 五华县| 当雄县| 台前县| 绥棱县| 万源市| 绥阳县| 枞阳县| 石台县| 讷河市|