1920. Build Array from Permutation #1650
-
Topics: Given a zero-based permutation A zero-based permutation Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to build an array Approach
Let's implement this solution in PHP: 1920. Build Array from Permutation <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function buildArray($nums) {
$ans = array();
for ($i = 0; $i < count($nums); $i++) {
$ans[$i] = $nums[$nums[$i]];
}
return $ans;
}
// Test case 1
$nums1 = array(0, 2, 1, 5, 3, 4);
print_r(buildArray($nums1)); // Output: [0, 1, 2, 4, 5, 3]
// Test case 2
$nums2 = array(5, 0, 1, 2, 3, 4);
print_r(buildArray($nums2)); // Output: [4, 5, 0, 1, 2, 3]
?> Explanation:
This approach efficiently constructs the result array in linear time, ensuring that each element is transformed correctly according to the problem's requirements. |
Beta Was this translation helpful? Give feedback.
We need to build an array
ans
from a given zero-based permutationnums
such that each elementans[i]
is equal tonums[nums[i]]
. The solution involves iterating through the input array and constructing the result array using the specified transformation.Approach
nums
such that each element in the resulting arrayans
at indexi
is the element innums
at the index specified by the element innums
at indexi
. This can be succinctly expressed asans[i] = nums[nums[i]]
.