2295. Replace Elements in an Array Medium
1/**
2 * [2295] Replace Elements in an Array
3 *
4 * You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the i^th operation you replace the number operations[i][0] with operations[i][1].
5 * It is guaranteed that in the i^th operation:
6 *
7 * operations[i][0] exists in nums.
8 * operations[i][1] does not exist in nums.
9 *
10 * Return the array obtained after applying all the operations.
11 *
12 * Example 1:
13 *
14 * Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]
15 * Output: [3,2,7,1]
16 * Explanation: We perform the following operations on nums:
17 * - Replace the number 1 with 3. nums becomes [<u>3</u>,2,4,6].
18 * - Replace the number 4 with 7. nums becomes [3,2,<u>7</u>,6].
19 * - Replace the number 6 with 1. nums becomes [3,2,7,<u>1</u>].
20 * We return the final array [3,2,7,1].
21 *
22 * Example 2:
23 *
24 * Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]
25 * Output: [2,1]
26 * Explanation: We perform the following operations to nums:
27 * - Replace the number 1 with 3. nums becomes [<u>3</u>,2].
28 * - Replace the number 2 with 1. nums becomes [3,<u>1</u>].
29 * - Replace the number 3 with 2. nums becomes [<u>2</u>,1].
30 * We return the array [2,1].
31 *
32 *
33 * Constraints:
34 *
35 * n == nums.length
36 * m == operations.length
37 * 1 <= n, m <= 10^5
38 * All the values of nums are distinct.
39 * operations[i].length == 2
40 * 1 <= nums[i], operations[i][0], operations[i][1] <= 10^6
41 * operations[i][0] will exist in nums when applying the i^th operation.
42 * operations[i][1] will not exist in nums when applying the i^th operation.
43 *
44 */
45pub struct Solution {}
46
47// problem: https://leetcode.com/problems/replace-elements-in-an-array/
48// discuss: https://leetcode.com/problems/replace-elements-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query=
49
50// submission codes start here
51use std::collections::HashMap;
52
53impl Solution {
54 pub fn array_change(nums: Vec<i32>, operations: Vec<Vec<i32>>) -> Vec<i32> {
55 let mut map: HashMap<i32, usize> = HashMap::new();
56 for (i, v) in nums.iter().enumerate() {
57 map.insert(*v, i);
58 }
59
60 let mut result = nums.clone();
61
62 for o in operations {
63 // garentee exist.
64 let index = map.get(&o[0]).unwrap();
65 result[*index] = o[1];
66 // mutable_borrow_reservation_conflict
67 let index_d = *index;
68 map.insert(o[1], index_d);
69 }
70 result
71 }
72}
73
74// submission codes end
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn test_2295() {
82 assert_eq!(
83 Solution::array_change(vec![1, 2, 4, 6], vec![vec![1, 3], vec![4, 7], vec![6, 1]]),
84 vec![3, 2, 7, 1]
85 );
86 }
87}
88
Back
© 2025 bowen.ge All Rights Reserved.