Leetcode 1920. Build Array from Permutation
You are given a zero-indexed array nums
of size n
consisting of distinct integers from 0
to n - 1
. You need to build a new array ans
where ans[i] = nums[nums[i]]
for each 0 <= i < n
and return it.
0
to n-1
without duplicates?nums
?n = 1
)?nums
.i
, we compute ans[i]
such that ans[i] = nums[nums[i]]
.ans
of the same length as nums
.nums
.i
, assign ans[i]
the value of nums[nums[i]]
.nums
are distinct and from 0
to n-1
, there is no out-of-bound access.#include <vector>
using namespace std;
class Solution {
public:
vector<int> buildArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
ans[i] = nums[nums[i]];
}
return ans;
}
};
nums
exactly once, performing a constant-time operation nums[nums[i]]
for each element.ans
of the same length as the input array nums
.nums
.i
, ans[i]
is set to nums[nums[i]]
as per the problem statement.ans
.This approach ensures that the solution is efficient and meets the constraints of the problem effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?