1920: Build-Array-from-Permutation
Easy
My in-place solution was high-key bad, but here it is.
I wanted to iterate through nums and be able to check which numbers that I have permuted already, which is why I convert every number into a negative number before hand.
That way, I know that if the number is negative it has not been permuted, else we can skip past it and work on permuting the next cycle.
Then, if we are in a new cycle, we can just simply iterate through them and swap all the numbers until we return back to the original index.
Code:
class Solution {
public:
<int> buildArray(vector<int>& nums) {
vectorfor (int& num : nums) {
= -(num+1);
num }
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] >= 0) continue;
int original_value = -nums[i]-1;
int original_index = i;
int new_index = original_value;
while (new_index != i) {
[original_index] = -nums[new_index]-1;
nums= new_index;
original_index = -nums[new_index]-1;
new_index }
[original_index] = original_value;
nums}
return nums;
}
};
Complexity:
Learnings:
class Solution {
public:
<int> buildArray(vector<int>& nums) {
vectorfor (int i = 0; i < nums.size(); ++i) {
[i] |= nums[0xFFFF & nums[i]] << 16;
nums}
for (int& num : nums) {
>>= 16;
num }
return nums;
}
};