Java O(1) space, one pass solution


  • 0
    Z

    Happy New Year everybody!!! I have decided to share my solution, because I haven't found similar implementation. It solves the problem in one pass.

    public class Solution {
        public void rotate(int[] nums, int k) {
            if(nums == null || nums.length == 0 || k == 0) return;
            int count = 0;
            int start = 0;
            int n = nums.length;
            while(count < n){
                    int cur = start;
                    int next = (cur+k)%n;
                    int val = nums[cur];
                    while(count < n && next != start){
                        int tmp = nums[next];
                        nums[next] = val;
                        val = tmp;
                        cur = next;
                        next = (cur+k)%n;
                        count++;
                    }
                    if(next == start){
                        nums[start] = val;
                        count++;
                    }
                    start++;
            }
        }
    }

Log in to reply
 

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