Initial Setup: Given an array nums, an integer k, and an integer multiplier, we need to find the minimum element in nums and replace it with its product with multiplier. This process is done k times.
Finding the Minimum: We need to find the minimum element and its first occurrence. This can be achieved by iterating through the array.
Replace the Element: Replace the found minimum element by multiplying it with multiplier.
Repeat: Repeat the above steps k times.
Optimization: Ensure that the process efficiently handles the array and doesn’t result in redundant searches.
classSolution {
publicint[]getFinalState(int[] nums, int k, int multiplier) {
// Creating a PriorityQueue with a custom comparator for (value, index) pairs PriorityQueue<int[]> minHeap =new PriorityQueue<>((a, b) -> a[0]!= b[0]? a[0]- b[0] : a[1]- b[1]);
// Adding elements to the heap as (value, index) pairsfor (int i = 0; i < nums.length; i++) {
minHeap.offer(newint[] { nums[i], i });
}
// Perform k operationswhile (k > 0) {
int[] min = minHeap.poll();
int num = min[0];
int idx = min[1];
// Update the value in the nums array nums[idx]= num * multiplier;
// Push the new value back into the heap minHeap.offer(newint[] { nums[idx], idx });
k--;
}
return nums;
}
}
classSolution {
publicint[]getFinalState(int[] nums, int k, int multiplier) {
// Creating a PriorityQueue with a custom comparator for (value, index) pairs PriorityQueue<int[]> minHeap =new PriorityQueue<>((a, b) -> a[0]!= b[0]? a[0]- b[0] : a[1]- b[1]);
// Adding elements to the heap as (value, index) pairs minHeap.addAll(IntStream.range(0, nums.length)
.mapToObj(i ->newint[]{nums[i], i})
.toList());
// Perform k operationswhile (k > 0) {
int[] min = minHeap.poll();
int num = min[0];
int idx = min[1];
// Update the value in the nums array nums[idx]= num * multiplier;
// Push the new value back into the heap minHeap.offer(newint[] { nums[idx], idx });
k--;
}
return nums;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defgetFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
# Creating a heap of (number, index) pairs heap = [(num, i) for i, num in enumerate(nums)]
heapq.heapify(heap)
# Perform k operationswhile k >0:
num, idx = heapq.heappop(heap)
# Update the value in the array nums[idx] = num * multiplier
# Push the new value back into the heap heapq.heappush(heap, (nums[idx], idx))
k -=1return nums