[LeetCode] Replace Elements in an Array

2295. Replace Elements in an Array

You are given a 0-indexed array nums that consists of n distinct 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> arrayChange(vector<int>& A, vector<vector<int>>& O) {
unordered_map<int, int> mp;
int n = A.size(), m = O.size();
for(int i = 0; i < n; i++) {
mp[A[i]] = i;
}

for(auto o : O) {
int f = o[0], t = o[1];
int idx = mp[f];
A[idx] = t;
mp.erase(f);
mp[t] = idx;
}

return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/replace-elements-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.