Created
February 7, 2025 01:20
-
-
Save ag8023/ae52d639b2f2dda2c199b92cb043e651 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void reverse(vector<int> &nums, int start, int end){ | |
while(start < end){ | |
swap(nums[start], nums[end]); | |
start++; | |
end--; | |
} | |
} | |
void rotate(vector<int>& nums, int k) { | |
k = k%nums.size(); // to get the actual rotation pattern | |
//brute force | |
int n = nums.size(); | |
// vector<int> temp(k); | |
// // first move the last k elements to temp (since we are doing a right shift) | |
// for(int i = 0; i < k; i++){ | |
// temp[i] = nums[(n-k)+ i]; | |
// cout << temp[i] << endl; | |
// } | |
// for(const auto &elem : nums){ | |
// cout << elem << " " << endl; | |
// } | |
// // now shift the first n-k elements of the input vector to the back of the array | |
// for(int i = 0 ; i < n-k; i++){ | |
// cout << n-k-1 << " + " << i << " = " << nums[n-k-1 + i] << endl; | |
// cout << nums[i] << endl; | |
// nums[n-k-1 + i] = nums[i]; | |
// } | |
// // now copy back the contents of temp at the front of the arrya(since we are doing a right shift) | |
// for(int i = 0; i < k; i++){ | |
// nums[i] = temp[i]; | |
// } | |
//optimal solution | |
reverse(nums, 0, n-1); | |
for(const auto &elem : nums){ | |
cout << elem << " " << endl; | |
} | |
reverse(nums, 0, k-1); | |
reverse(nums, k, n-1); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am unable to get my brute force solution to work, need help with that.