Online Judge Solutions

Wednesday, February 25, 2015

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
class Solution {
    void rotateHelper(int A[], int k, int n)
    {
        int i = 0;
        while(i + k < n) 
        {
            int count = 0;
            for(; i+k < n; i++) {
                int t = A[i];
                A[i] = A[i+k];
                A[i+k] = t;
                count++;
            }   
            
            k = k - count % k; 
        }
    }


public:
    /**
     * param A: A string
     * param offset: Rotate string with offset.
     * return: Rotated string.
     */
     void rotate(int A[], int n, int k) {
        if (n < 2) return ;
        int K = n - k % n;
        
        rotateHelper(A, K, n); 
    }
};

No comments:

Post a Comment