C++ simple solution use inverse method


  • 2
    L
    class Solution {
    public:
        void rotate(int nums[], int n, int k) {
        	k %= n; // there is a trap
    
        	if (k == 0) { // there is a trap when k == 0
        		return;
        	}
    
        	int gap = n - k; 
            inverse(nums, 0, gap);
            inverse(nums, gap, n);
            inverse(nums, 0, n);
        }
    
        void inverse(int nums[], int s, int e) {
        	--e;
        	while (s < e) {
        		int tmp = nums[s];
        		nums[s] = nums[e];
        		nums[e] = tmp;
        		++s;
        		--e;
        	}
        }
    };

  • 0
    K

    Thank you, very clean solution!


  • 0
    R

    What's the trap when k == 0?
    Without checking k==0, the second inverse will not be excuted


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.