LeetCode in Kotlin

2295. Replace Elements in an Array

Medium

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:

Return the array obtained after applying all the operations.

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:

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:

We return the array [2,1].

Constraints:

Solution

class Solution {
    fun arrayChange(nums: IntArray, operations: Array<IntArray>): IntArray {
        val map = HashMap<Int, Int>()
        for (i in nums.indices) {
            map[nums[i]] = i
        }
        for (operation in operations) {
            val index = map[operation[0]]!!
            nums[index] = operation[1]
            map[operation[1]] = index
        }
        return nums
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy