Choose to code non-trivial algorithm for this. (Java), Please let me know if I can improve anything in the code.


  • 0
    V
    public class Solution {
        public void rotate(int[] nums, int k) {
            int n = nums.length;
            k = k % n;
            
            if (k > 0) {
                rotate(nums, 0, n - 1, k, 1);
            }
        }
        
        private void rotate(int[] A, int start, int end, int k, int rotation) {
            if (end > start) {
                int len = end - start + 1;
                if (len == (k << 1)) {
                    swap(A, start, start + (len >> 1), end);
                } else {
                    if (len < (k << 1)) {
                        k = len - k;
                        rotation = rotation ^ 1;
                    }
                    if (rotation == 1) {
                        swap(A, end - 2 * k + 1, end - k + 1, end);
                        rotate(A, start, end - k, k, rotation);
                    } else {
                        swap(A, start, start + k, start + 2 * k - 1);
                        rotate(A, start + k, end, k, rotation);
                    }
                }
            }
        }
        
        private void swap(int[] A, int start, int mid, int end) {
            int i = 1;
            while(end >= mid) {
                int tmp = A[end];
                A[end] = A[mid - i];
                A[mid - i] = tmp;
                i++;
                end --;
            }
        }
    }
    

Log in to reply
 

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