LeetCode # Array # Easy # 189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
题目:给定一个数组和一个数值k,要求将数组向右旋转k步。
以前准备面试时看到过这个题目,结果今天还是记不得空间复杂度O(1)的解法,好记性不如烂笔头。
思路:三次翻转数组,首先将整个数组逆序;然后将数组前k个逆序;最后将数组后n-k个逆序。
1 class Solution { 2 private void reverse(int[] nums, int start, int end) { 3 while(start < end){ 4 int tmp = nums[start]; 5 nums[start] = nums[end]; 6 nums[end] = tmp; 7 start ++; 8 end --; 9 } 10 } 11 public void rotate(int[] nums, int k) { 12 int n = nums.length; 13 if(n == 1){ 14 return; 15 } 16 k = k%n; 17 reverse(nums, 0, n-1); 18 reverse(nums, 0, k-1); 19 reverse(nums, k, n-1); 20 } 21 }
参考:https://leetcode.com/problems/rotate-array/discuss/127941/Java-1ms.-Done-In-place.-Used-reversal-algorithm.