189. Rotate Array

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

翻转三次就好了 第一次0----len-1,第二次0-----k-1,第三次k---len-1,
主要注意交换函数不要写错就好了。
交换的次数是N/2;
可以采用双指针法

class Solution {
    public void rotate(int[] nums, int k) {
      k = k%nums.length;
        // in  case overflow
       rotate_0_n(nums,0,nums.length-1);
       rotate_0_n(nums,0,k-1);
       rotate_0_n(nums,k,nums.length-1);

    }
    private void rotate_0_n (int[] nums,int start,int end)
    {
          while(start<=end)
        {
            int temp = nums[start];
            nums[start]=nums[end];
            nums[end]=temp;
              start++;
              end--;
        }
    }
}

你可能感兴趣的:(189. Rotate Array)