mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 0300.最长上升子序列.md
This commit is contained in:
@ -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
|
||||
// 动态规划求解
|
||||
|
Reference in New Issue
Block a user