|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/build-array-from-permutation/ |
| 3 | +
|
| 4 | +Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] |
| 5 | +for each 0 <= i < nums.length and return it. |
| 6 | +A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +Input: nums = [0,2,1,5,3,4] |
| 10 | +Output: [0,1,2,4,5,3] |
| 11 | +Explanation: 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] |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: nums = [5,0,1,2,3,4] |
| 18 | +Output: [4,5,0,1,2,3] |
| 19 | +Explanation: The array ans is built as follows: |
| 20 | +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] |
| 21 | + = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] |
| 22 | + = [4,5,0,1,2,3] |
| 23 | +
|
| 24 | +Constraints: |
| 25 | +1 <= nums.length <= 1000 |
| 26 | +0 <= nums[i] < nums.length |
| 27 | +The elements in nums are distinct. |
| 28 | + |
| 29 | +Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)? |
| 30 | +""" |
| 31 | +class Solution: |
| 32 | + def buildArray(self, nums: List[int]) -> List[int]: |
| 33 | + l = len(nums) |
| 34 | + |
| 35 | + for index in range(l): |
| 36 | + nums[index] += l * (nums[nums[index]] % l) |
| 37 | + |
| 38 | + for index in range(l): |
| 39 | + nums[index] //= l |
| 40 | + |
| 41 | + return nums |
| 42 | + |
| 43 | + |
| 44 | +class Solution1: |
| 45 | + def buildArray(self, nums: List[int]) -> List[int]: |
| 46 | + return [nums[index] for index in nums] |
| 47 | + |
0 commit comments