C++ O(n) easy understand


  • 0
    D
    public:
        int index(int size, int k, int i){
            return (i - k < 0)? size - k + i: i- k;
        }
        void rotate(vector<int>& nums, int k) {
            int size = nums.size();
            if(size == k || k == 0 || size == 1) return;
            vector<int> tmp(size, 0);
            if( k > size) k = k -size;
            for(int i = 0; i < size; ++i){
                tmp[i] = nums[index(size,k,i)];
            }
            nums = tmp;
        }
    };

Log in to reply
 

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