From d3a07fa1bd7c325188a416486daa7a85e6816680 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Tue, 6 Jun 2023 15:29:07 -0500 Subject: [PATCH] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF=E4=B8=8A?= =?UTF-8?q?=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...07\345\255\220\345\272\217\345\210\227.md" | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git "a/problems/0300.\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227.md" "b/problems/0300.\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227.md" index 01d349496b..98d7b14ffb 100644 --- "a/problems/0300.\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227.md" +++ "b/problems/0300.\346\234\200\351\225\277\344\270\212\345\215\207\345\255\220\345\272\217\345\210\227.md" @@ -141,7 +141,7 @@ class Solution { } } ``` - +DP Python: ```python class Solution: @@ -157,7 +157,31 @@ class Solution: result = max(result, dp[i]) #取长的子序列 return result ``` +贪心 +```python +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + if len(nums) <= 1: + return len(nums) + + tails = [nums[0]] # 存储递增子序列的尾部元素 + for num in nums[1:]: + if num > tails[-1]: + tails.append(num) # 如果当前元素大于递增子序列的最后一个元素,直接加入到子序列末尾 + else: + # 使用二分查找找到当前元素在递增子序列中的位置,并替换对应位置的元素 + left, right = 0, len(tails) - 1 + while left < right: + mid = (left + right) // 2 + if tails[mid] < num: + left = mid + 1 + else: + right = mid + tails[left] = num + + return len(tails) # 返回递增子序列的长度 +``` Go: ```go // 动态规划求解