알고리즘
Build Array from Permutation
짬뽕얼큰하게
2025. 5. 6. 23:14
Leetcode Problem:
Summary
- Given a zero-based permutation, build an array where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
Approach
- This solution uses a simple iterative approach where it iterates over the input array and uses the value at each index as the index for the next value in the output array.
Complexity
- O(n) where n is the length of the input array
Explanation
- The solution uses a vector to store the output array and iterates over the input array
- For each index in the input array, it uses the value at that index as the index for the next value in the output array
- This approach is simple and efficient, with a time complexity of O(n) where n is the length of the input array.
Solution Code:
class Solution {
public:
vector ans;
vector buildArray(vector& nums) {
for(int i = 0 ; i < nums.size(); i++){
ans.push_back(nums[nums[i]]);
}
return ans;
}
};
class Solution {
public:
vector ans;
vector buildArray(vector& nums) {
for(int i = 0 ; i < nums.size(); i++){
ans.push_back(nums[nums[i]]);
}
return ans;
}
};