Only visit each node once. and space O(0)


  • 1
    B
    public class Solution
    {
        public void Rotate(int[] nums, int k)
        {
            if (nums == null || nums.Length == 0)
            {
                return;
            }
            int smallestIndex = k % nums.Length;
    
            for (int j = 0; j < smallestIndex; j++)
            {
                int i = j;
                int previousValue = nums[i];
                do
                {
                    int next = i + k;
    
                    next = next % nums.Length;
                    
                    var temp = nums[next];
                    nums[next] = previousValue;
                    previousValue = temp;
                    if (next < smallestIndex && next != j)
                    {
                        smallestIndex = next;
                    }
                    i = next;
                }
                while (i != j);
            }
        }
    }

Log in to reply
 

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