#2295

Replace Elements in an Array

specialist · 720 · lc medium +30 · verified · 59.6% accepted · 681 likes · top 57%

Description

You are given a 0-indexed array nums of n distinct positive integers, and a 2D array operations where each entry instructs you to replace one value with another.

For each operation [operations[i][0], operations[i][1]]:

- operations[i][0] is guaranteed to exist in the current nums.

- operations[i][1] is guaranteed not to exist in the current nums.

Return the array after all operations have been applied.

Example 1:

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 1 with 3. nums becomes [3,2,4,6].
- Replace the number 4 with 7. nums becomes [3,2,7,6].
- Replace the number 6 with 1. nums becomes [3,2,7,1].
We return the final array [3,2,7,1].

Example 2:

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 1 with 3. nums becomes [3,2].
- Replace the number 2 with 1. nums becomes [3,1].
- Replace the number 3 with 2. nums becomes [2,1].
We return the array [2,1].

Code

1
2
3