JimYuan's Blog

Sharing the things I learned

0%

shift_list_rotate_Array

Preface

In grasshopper, there’s one component called shift_list and basically it did things like Rotate_Array. People can plug in one number and make the list shift/rotate with that number.
Recently, I am trying to catch up some algorithms from Leetcode, and Rotate_Array is one of them.


Example:
Input:
[1,2,3,4,5]
3

Output:
[4,5,1,2,3]


There are obviously some solution for this question. The one I am looking for is the one can acchieve in_place property.

1
2
3
4
5
6
7
8
public:
void rotate(vector<int>& nums, int k) {
k %= nums.size();
reverse(nums.begin(),nums.end());
reverse(nums.begin(),nums.begin()+k);
reverse(nums.begin()+k,nums.end());
}
};

Reference

https://leetcode.com/problems/rotate-array/
https://www.geeksforgeeks.org/array-rotation/
https://leetcode.com/problems/rotate-array/discuss/1729976/C%2B%2B-or-O(N)-or-GCD