Skip to content

Commit

Permalink
Create replace-elements-in-an-array.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jun 8, 2022
1 parent 4e9ac49 commit 92ef89b
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions Python/replace-elements-in-an-array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Time: O(n + m)
# Space: O(n)

# hash table, optimized from solution2
class Solution(object):
def arrayChange(self, nums, operations):
"""
:type nums: List[int]
:type operations: List[List[int]]
:rtype: List[int]
"""
lookup = {x:i for i, x in enumerate(nums)}
for x, y in operations:
lookup[y] = lookup.pop(x)
for x, i in lookup.iteritems():
nums[i] = x
return nums


# Time: O(n + m)
# Space: O(n)
# hash table
class Solution2(object):
def arrayChange(self, nums, operations):
"""
:type nums: List[int]
:type operations: List[List[int]]
:rtype: List[int]
"""
lookup = {x:i for i, x in enumerate(nums)}
for x, y in operations:
nums[lookup[x]] = y
lookup[y] = lookup.pop(x)
return nums

0 comments on commit 92ef89b

Please sign in to comment.