fork download
  1. #include<bits/stdc++.h>
  2. // #include<leetcode.h>
  3. #define null NULL
  4. #define endl '\n'
  5. #define ll long long
  6. using namespace std;
  7. #define goF(i, a, b) for(int i=a; i<b; i++)
  8. #define goB(i, a, b) for(int i=a; i>=b; i--)
  9.  
  10.  
  11. /*
  12. *For Forward Shifting: Reverse K elements from the FRONT
  13. *For Backward Shifting: Reverse K elements from the BACK
  14. */
  15.  
  16. //TC: O(N), SC:O(1)
  17. void reverse(vector<int>& nums, int start, int end){
  18. while(start <= end){
  19. swap(nums[start++], nums[end--]);
  20. }
  21. }
  22. void fwdShift(vector<int>& nums, int k){
  23. int n = nums.size();
  24. k %= n;
  25.  
  26. //reverse(nums, 0, n-1);
  27. reverse(nums.begin(), nums.end());
  28.  
  29. //*Reverse K elements from the FRONT
  30. //reverse(nums, 0, k-1);
  31. reverse(nums.begin(), nums.begin()+k);
  32.  
  33.  
  34. //reverse(nums, k, n-1);
  35. reverse(nums.begin()+k, nums.end());
  36. }
  37. void bckwdShift(vector<int>& nums, int k){
  38. int n = nums.size();
  39. k %= n;
  40.  
  41. //reverse(nums, 0, n-1);
  42. reverse(nums.begin(), nums.end());
  43.  
  44. //*Reverse K elements from the BACK
  45. //reverse(nums, n-k, n-1);
  46. reverse(nums.begin()+n-k, nums.end());
  47.  
  48. //reverse(nums, 0, n-k-1);
  49. reverse(nums.begin(), nums.begin()+n-k);
  50. }
  51.  
  52. class Solution{
  53. private:
  54. void reverse(vector<int>& nums, int start, int end){
  55. while(start <= end){
  56. swap(nums[start++], nums[end--]);
  57. }
  58. }
  59.  
  60. public:
  61. void rotate(vector<int>& nums, int k){//fwd shifting
  62. int n = nums.size();
  63. k %= n;
  64.  
  65. reverse(nums, 0, n-1);
  66. //reverse(nums.begin(), nums.end());
  67.  
  68. //*Reverse K elements from the FRONT
  69. reverse(nums, 0, k-1);
  70. //reverse(nums.begin(), nums.begin()+k);
  71.  
  72.  
  73. reverse(nums, k, n-1);
  74. //reverse(nums.begin()+k, nums.end());
  75. }
  76. };
  77.  
  78.  
  79. int main(){
  80.  
  81. vector<int> nums1 = {1, 2, 3, 4, 5, 6, 7};
  82. vector<int> nums2 = nums1;
  83.  
  84. int k = 1;
  85.  
  86. fwdShift(nums1, k);
  87. for(int x: nums1) cout<<x<<" ";
  88. cout<<endl;
  89.  
  90. k = 6;
  91. bckwdShift(nums2, k);
  92. for(int x: nums2) cout<<x<<" ";
  93. cout<<endl;
  94.  
  95. cout<<"\nGo Google!"<<endl;
  96. return 0;
  97. }
  98.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
7 1 2 3 4 5 6 
7 1 2 3 4 5 6 

Go Google!