当前位置:网站首页>LeetCode简单题之找到和最大的长度为 K 的子序列
LeetCode简单题之找到和最大的长度为 K 的子序列
2022-07-31 02:56:00 【·星辰大海】
题目
给你一个整数数组 nums 和一个整数 k 。你需要找到 nums 中长度为 k 的 子序列 ,且这个子序列的 和最大 。
请你返回 任意 一个长度为 k 的整数子序列。
子序列 定义为从一个数组里删除一些元素后,不改变剩下元素的顺序得到的数组。
示例 1:
输入:nums = [2,1,3,3], k = 2
输出:[3,3]
解释:
子序列有最大和:3 + 3 = 6 。
示例 2:
输入:nums = [-1,-2,3,4], k = 3
输出:[-1,3,4]
解释:
子序列有最大和:-1 + 3 + 4 = 6 。
示例 3:
输入:nums = [3,4,3,3], k = 2
输出:[3,4]
解释:
子序列有最大和:3 + 4 = 7 。
另一个可行的子序列为 [4, 3] 。
提示:
1 <= nums.length <= 1000
-10^5 <= nums[i] <= 10 ^5
1 <= k <= nums.length
来源:力扣(LeetCode)
解题思路
这个题所要求的结果数组在原数组中是不需要连续的,这样就大大降低了题目的难度,所以第一步可以先将给定的数组排序,然后取出最大的几个元素和它们的下标,然后在截取符合条件的结果并返回正确的在原数组中的先后顺序。
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
new_nums=sorted(enumerate(nums),key=lambda x:-x[1])
ans=sorted(new_nums[0:k],key=lambda x:x[0])
return [i[1] for i in ans]

当然这道题其实是不需要完全将排序做完的,最好的方法就是用选择排序将符合条件的k个选出来后便不再继续排序。
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
ans=[]
for i in range(k):
MAX,index=-float('inf'),-1
for j in enumerate(nums):
if j[1]!=None:
if j[1]>MAX:
MAX,index=j[1],j[0]
ans.append((index,MAX))
nums[index]=None
return [i[1] for i in sorted(ans)]

边栏推荐
- SQL injection Less54 (limited number of SQL injection + union injection)
- Clustering index, and what is the difference between a clustering index
- 【C语言基础】解决C语言error: expected ‘;‘, ‘,‘ or ‘)‘ before ‘&‘ token
- Go 项目实战-获取多级分类下的全部商品
- 11. Redis implements follow, unfollow, and follow and follower lists
- C#远程调试
- LeetCode 1161 最大层内元素和[BFS 二叉树] HERODING的LeetCode之路
- 12 磁盘相关命令
- return in try-catch
- SQL 面试用题(重点)
猜你喜欢
随机推荐
【C语言】求两个整数m和n的最大公因数和最小公倍数之和一般方法,经典解法
The simulation application of common mode inductance is here, full of dry goods for everyone
自动化办公案例:如何自动生成期数据?
AI中的数学思想
Mysql 45讲学习笔记(二十三)MYSQL怎么保证数据不丢
医疗影像领域AI软件开发流程
Modbus on AT32 MCU
开题报告之论文框架
BAT can't sell "Medical Cloud": Hospitals flee, mountains stand, and there are rules
学习DAVID数据库(1)
12 磁盘相关命令
经典链表OJ强训题——快慢双指针高效解法
品牌广告投放平台的中台化应用与实践
【C语言基础】解决C语言error: expected ‘;‘, ‘,‘ or ‘)‘ before ‘&‘ token
2022牛客多校联赛第四场 题解
AI在医疗影像设备全流程应用
Why is String immutable?
execsnoop tool
【C语言】三子棋(经典解法+一览图)
8. Unified exception handling (controller notifies @ControllerAdvice global configuration class, @ExceptionHandler handles exceptions uniformly)









