leetcode在力扣 App 中打开
调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
简单
相关标签
相关企业
提示

给你一个正整数数组 nums 和一个整数 k 。

一次操作中,你可以将数组的最后一个元素删除,将该元素添加到一个集合中。

请你返回收集元素 1, 2, ..., k 需要的 最少操作次数 。

 

示例 1:

输入:nums = [3,1,5,4,2], k = 2
输出:4
解释:4 次操作后,集合中的元素依次添加了 2 ,4 ,5 和 1 。此时集合中包含元素 1 和 2 ,所以答案为 4 。

示例 2:

输入:nums = [3,1,5,4,2], k = 5
输出:5
解释:5 次操作后,集合中的元素依次添加了 2 ,4 ,5 ,1 和 3 。此时集合中包含元素 1 到 5 ,所以答案为 5 。

示例 3:

输入:nums = [3,2,5,3,1], k = 3
输出:4
解释:4 次操作后,集合中的元素依次添加了 1 ,3 ,5 和 2 。此时集合中包含元素 1 到 3  ,所以答案为 4 。

 

提示:

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= nums.length
  • 1 <= k <= nums.length
  • 输入保证你可以收集到元素 1, 2, ..., k
通过次数
5.9K
提交次数
8.3K
通过率
71.2%


相关企业

提示 1
Use an occurrence array.

提示 2
Iterate over the elements in reverse order.

提示 3
If the current element nums[i] is not marked in the occurrence array and nums[i] <= k, mark nums[i].

提示 4
Keep track of how many integers you have marked.

提示 5
Return the current index as soon as the number of marked integers becomes equal to k.

相似题目

评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
2 人在线
行 1,列 1
nums =
[3,1,5,4,2]
k =
2
Source