My C and C++ and python answer


  • 1
    S

    C

    void rotate(int nums[], int n, int k) {
    	k %= n;
    	if (k)
    	{
    		int *v = (int*)malloc(k*sizeof(int));
    		memcpy(v, nums + n - k, k*sizeof(int));
    		memcpy(nums+k, nums, (n-k)*sizeof(int));
    		memcpy(nums, v, k*sizeof(int));
    		free(v);
    	}
    }
    

    C++

    class Solution {
    public:
        void rotate(int nums[], int n, int k) {
            k %= n;
        	if (k)
        	{
        		std::vector<int> v(nums, nums + n);
        		std::copy(v.begin() + n - k, v.end(), nums);
        		std::copy(v.begin(), v.begin() + n - k, nums+k);
        	}
        }
    };
    

    python

    class Solution:
        # @param nums, a list of integer
        # @param k, num of steps
        # @return nothing, please modify the nums list in-place.
        def rotate(self, nums, k):
            k = k % len(nums)
            if k:
                nums[:] = nums[-k:] + nums[0:(len(nums)-k)]

  • 1
    C

    In case of python following also works:

    nums[:] = nums[-k:]+nums[:-k]

  • 0
    S

    yes, you are right :)


Log in to reply
 

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