Skip to content

Commit 04853bd

Browse files
authored
Merge pull request larissalages#243 from SouravCodery/patch-1
Create 189. Rotate Array.cpp
2 parents 9e4011c + 2b812e1 commit 04853bd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
void reverse(vector<int> &nums, int startIndex, int endIndex)
4+
{
5+
//This function reverses the vector for the given start and end Indices of the Vector
6+
while(startIndex < endIndex)
7+
{
8+
int temp = nums[startIndex];
9+
nums[startIndex] = nums[endIndex];
10+
nums[endIndex] = temp;
11+
12+
startIndex++;
13+
endIndex--;
14+
}
15+
}
16+
void rotate(vector<int>& nums, int k)
17+
{
18+
int length = nums.size(); //Stores the Size of the Vector into the length variable
19+
if(k > length)
20+
{
21+
k %= length; //Making Sure that the Rotation is within the length of the Vector
22+
}
23+
if(k == 0 || k == length) //If k is zero or k is equal to the length of the Vector there is no need to perform operations on it
24+
return;
25+
26+
//Rotating the Vector with the help of the Reverse Function
27+
reverse(nums, 0, length - 1);
28+
reverse(nums, 0, k - 1);
29+
reverse(nums, k, length - 1);
30+
}
31+
};

0 commit comments

Comments
 (0)