This article is participating in Python Theme Month. See the link for details

describe

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.

A zero-based permutation nums is an array of distinct integers from 0 to nums.length – 1 (inclusive).

Example 1:

Input: nums = [0,2,1,5,3,4] Output: [0,1,2,4,5,3] Explanation: The array ans is built as follows: ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] = [nums[0], nums[2], Nums nums [1], [5], nums [3], nums =,1,2,4,5,3 [0] [4]]Copy the code

Example 2:

Input: nums = [5,0,1,2,3,4] Output: [4,5,0,1,2,3] Explanation: The array ans is built as follows: ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] = [nums[5], nums[0], Nums nums [1], [2], nums [3], nums =,5,0,1,2,3 [4] [4]]Copy the code

Note:

1 <= nums.length <= 1000
0 <= nums[i] < nums.length
The elements in nums are distinct.
Copy the code

parsing

Nums [I]]; nums[I]; nums[I]; nums[I] Then append each nums[num] to result, and get the final answer at the end of the loop.

answer

class Solution(object):
    def buildArray(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        result = []
        for num in nums:
            result.append(nums[num])
        return result
        	      
		
Copy the code

The results

Given in the Python online submission to Build Array from Permutation. Given in the Python online submissions for Build Array from Permutation.Copy the code

parsing

The other method is to use the numpy technique, using numS itself as the index, and then using np.array(numS)[numS] to get the answer. By convention, this method is simple but not recommended. Here I make a simple explanation of numpy’s array technique, the code is as follows:

Example 1:

Import numpy as np a = np. Array ([5,2, 3]) print(a[[1,2]])Copy the code

Print:

2 [4]Copy the code

Example 2:

Import numpy as np a = np. Array ([5,2,4,3]) print(a[[0,1]])Copy the code

Print:

2 [5]Copy the code

The new array is obtained by passing the indexed list into the array constructed by Numpy.

As a result, this method is also slow and takes up a lot of memory.

answer

class Solution(object):
    def buildArray(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        import numpy as np
        return np.array(nums)[nums]
Copy the code

The results

Given in the Python online submission for Build Array from Permutation. Given in the Python online submissions for Build Array from Permutation.Copy the code

Original link: leetcode.com/problems/bu…

Your support is my biggest motivation