Friday, April 3, 2015

Rotate Array

Prob:
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].


Sol:
class Solution {
public:
    void rotate(int nums[], int n, int k) {
        int rotate_by = k % n;
        reverse(nums, 0, n);
        reverse(nums, 0, rotate_by);
        reverse(nums, rotate_by, n);
    }
    void reverse(int nums[], int start, int end) {
        while (start < end) {
            swap(&nums[start++], &nums[--end]);
        }
    }
    void swap(int *a, int *b) {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
};

No comments:

Post a Comment