You are given a 0-indexed array nums that consists of ndistinct positive integers. Apply m operations to this array, where in the ith
operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0]exists in nums.
operations[i][1] does not exist in nums.
Return the array obtained after applying all the operations.
Input: nums =[1,2,4,6], operations =[[1,3],[4,7],[6,1]]Output: [3,2,7,1]Explanation: We perform the following operations on nums:- Replace the number 1with3. nums becomes [_**3**_ ,2,4,6].- Replace the number 4with7. nums becomes [3,2,_**7**_ ,6].- Replace the number 6with1. nums becomes [3,2,7,_**1**_].We return the final array [3,2,7,1].
Input: nums =[1,2], operations =[[1,3],[2,1],[3,2]]Output: [2,1]Explanation: We perform the following operations to nums:- Replace the number 1with3. nums becomes [_**3**_ ,2].- Replace the number 2with1. nums becomes [3,_**1**_].- Replace the number 3with2. nums becomes [_**2**_ ,1].We return the array [2,1].
To efficiently replace elements in the array, we need to quickly find the index of the number to be replaced. Using a hash map from value to index allows O(1) updates for each operation.
import java.util.*;
publicclassSolution {
publicint[]arrayChange(int[] nums, int[][] operations) {
Map<Integer, Integer> pos =new HashMap<>();
for (int i = 0; i < nums.length; i++) pos.put(nums[i], i);
for (int[] op : operations) {
int idx = pos.get(op[0]);
nums[idx]= op[1];
pos.put(op[1], idx);
pos.remove(op[0]);
}
return nums;
}
}
1
2
3
4
5
6
7
8
9
10
11
funarrayChange(nums: IntArray, operations: Array<IntArray>): IntArray {
val pos = mutableMapOf<Int, Int>()
for (i in nums.indices) pos[nums[i]] = i
for (op in operations) {
val idx = pos[op[0]]!! nums[idx] = op[1]
pos[op[1]] = idx
pos.remove(op[0])
}
return nums
}
1
2
3
4
5
6
7
defarrayChange(nums, operations):
pos = {v: i for i, v in enumerate(nums)}
for old, new in operations:
idx = pos.pop(old)
nums[idx] = new
pos[new] = idx
return nums
1
2
3
4
5
6
7
8
9
10
use std::collections::HashMap;
fnarray_change(nums: &mut [i32], operations: &[[i32; 2]]) -> Vec<i32> {
letmut pos: HashMap<i32, usize>= nums.iter().enumerate().map(|(i, &v)| (v, i)).collect();
for op in operations {
let idx = pos.remove(&op[0]).unwrap();
nums[idx] = op[1];
pos.insert(op[1], idx);
}
nums.to_vec()
}