Input: nums =[3,1,5,4,2], k =2Output: 4Explanation: After 4 operations, we collect elements 2,4,5, and 1,inthis order. Our collection contains elements 1 and 2. Hence, the answer is4.
Input: nums =[3,1,5,4,2], k =5Output: 5Explanation: After 5 operations, we collect elements 2,4,5,1, and 3,inthis order. Our collection contains elements 1 through 5. Hence, the answer is5.
Input: nums =[3,2,5,3,1], k =3Output: 4Explanation: After 4 operations, we collect elements 1,3,5, and 2,inthis order. Our collection contains elements 1 through 3. Hence, the answer is4.
We need to collect all elements from 1 to k by removing elements from the end. The minimum number of operations is the number of steps needed to see all k elements when scanning from the end.
import java.util.*;
classSolution {
publicintminOperations(int[] nums, int k) {
Set<Integer> s =new HashSet<>();
int ans = 0;
for (int i = nums.length- 1; i >= 0; --i) {
if (1 <= nums[i]&& nums[i]<= k) s.add(nums[i]);
++ans;
if (s.size() == k) break;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminOperations(nums: IntArray, k: Int): Int {
val s = mutableSetOf<Int>()
var ans = 0for (i in nums.indices.reversed()) {
if (nums[i] in1..k) s.add(nums[i])
ans++if (s.size == k) break }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defminOperations(self, nums: list[int], k: int) -> int:
s = set()
ans: int =0for v in reversed(nums):
if1<= v <= k:
s.add(v)
ans +=1if len(s) == k:
breakreturn ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::collections::HashSet;
impl Solution {
pubfnmin_operations(nums: Vec<i32>, k: i32) -> i32 {
letmut s = HashSet::new();
letmut ans =0;
for&v in nums.iter().rev() {
if1<= v && v <= k {
s.insert(v);
}
ans +=1;
if s.len() == k asusize {
break;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
minOperations(nums: number[], k: number):number {
consts=newSet<number>();
letans=0;
for (leti=nums.length-1; i>=0; --i) {
if (1<=nums[i] &&nums[i] <=k) s.add(nums[i]);
++ans;
if (s.size===k) break;
}
returnans;
}
}