Given an integer array nums
, rotate the array to the right by k
steps, where k
is non-negative.
Example:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
#Solution in c++
class Solution {
public:
void rotate(vector<int>& nums, int k) {
// Get the size of the array
int n = nums.size();
// Create a new array to store rotated elements
vector<int> rotated(n);
// Loop through each element in the original array
for (int i = 0; i < n; ++i) {
// Calculate the new index after rotation
int newIndex = (i + k) % n;
// Assign the element to its new index in the rotated array
rotated[newIndex] = nums[i];
}
// Update the original array with the rotated elements
nums = rotated;
}
};
Explain solution :
1:Determine the size of the array:
Utilize the size method to ascertain the number of elements in the array.
2:Initialize a new array for shifted elements:
Create a new array with the same size as the original array to accommodate the elements after the desired shifting.
3:Iterate through each element in the original array:
Implement a loop to traverse through each element in the original array.
4:Calculate the new index for each element after shifting:
Employ a mathematical formula (i + k) % n to compute the new index for each element, considering the desired shift.
5:Assign each element to its new position in the new array:
Assign the elements to their recalculated indices in the new array, effectively mimicking the desired shift.
6:Update the original array with the recalculated positions:
Update the original array with the elements' new positions from the newly created array, finalizing the shift operation
if any one have better solution so please comment :)