Skip to content

Commit 77ac1db

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (44.72%), Memory - 18.1 MB (13.03%)
1 parent bba6de4 commit 77ac1db

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>Given a <strong>zero-based permutation</strong> <code>nums</code> (<strong>0-indexed</strong>), build an array <code>ans</code> of the <strong>same length</strong> where <code>ans[i] = nums[nums[i]]</code> for each <code>0 &lt;= i &lt; nums.length</code> and return it.</p>
2+
3+
<p>A <strong>zero-based permutation</strong> <code>nums</code> is an array of <strong>distinct</strong> integers from <code>0</code> to <code>nums.length - 1</code> (<strong>inclusive</strong>).</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [0,2,1,5,3,4]
10+
<strong>Output:</strong> [0,1,2,4,5,3]<strong>
11+
Explanation:</strong> The array ans is built as follows:
12+
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
13+
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
14+
= [0,1,2,4,5,3]</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [5,0,1,2,3,4]
20+
<strong>Output:</strong> [4,5,0,1,2,3]
21+
<strong>Explanation:</strong> The array ans is built as follows:
22+
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
23+
= [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
24+
= [4,5,0,1,2,3]</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
31+
<li><code>0 &lt;= nums[i] &lt; nums.length</code></li>
32+
<li>The elements in <code>nums</code> are <strong>distinct</strong>.</li>
33+
</ul>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Follow-up:</strong> Can you solve it without using an extra space (i.e., <code>O(1)</code> memory)?</p>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Approach 1: Build As Required
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def buildArray(self, nums: List[int]) -> List[int]:
8+
return [nums[i] for i in nums]
9+

0 commit comments

Comments
 (0)