forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace-elements-in-an-array.cpp
40 lines (38 loc) · 1.03 KB
/
replace-elements-in-an-array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(n + m)
// Space: O(n)
// hash table, optimized from solution2
class Solution {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
unordered_map<int, int> lookup;
for (int i = 0; i < size(nums); ++i) {
lookup[nums[i]] = i;
}
for (const auto& op : operations) {
int i = lookup[op[0]]; lookup.erase(op[0]);
lookup[op[1]] = i;
}
for (const auto& [x, i] : lookup) {
nums[i] = x;
}
return nums;
}
};
// Time: O(n + m)
// Space: O(n)
// hash table
class Solution2 {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
unordered_map<int, int> lookup;
for (int i = 0; i < size(nums); ++i) {
lookup[nums[i]] = i;
}
for (const auto& op : operations) {
int i = lookup[op[0]]; lookup.erase(op[0]);
nums[i] = op[1];
lookup[nums[i]] = i;
}
return nums;
}
};