leetcode-189-旋转数组
问题:
package com.example.demo; import sun.security.util.Length; public class Test189 { /** * 方法一:暴力解法 */ public void rotate(int[] nums, int k) { for (int i = 0; i < k; i++) { int pre = nums[nums.length - 1]; for (int j = 0; j < nums.length; j++) { int temp = nums[j]; nums[j] = pre; pre = temp; } } } /** * 方法二:使用额外数组法 */ public void rotate1(int[] nums, int k) { int len = nums.length; int[] res = new int[len]; for (int i = 0; i < len; i++) { res[(i + k) % len] = nums[i]; } for (int i = 0; i < len; i++) { nums[i] = res[i]; } } /** * 方法三:三步翻转法 ******** */ public void rotate2(int[] nums, int k) { int len = nums.length; //对k重新复制,放置数组越界,当len = 4时,k = 5和 k = 1的效果相同 k = k % len; reverseNums(nums, 0, len - 1); reverseNums(nums, 0, k - 1); reverseNums(nums, k, len - 1); } /** * 交换指定位置的值 */ private void reverseNums(int[] nums, int left, int right) { while (left <= right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } private void swapArr(int[] nums, int pointer, int cur) { int temp = nums[pointer]; nums[pointer] = nums[cur]; nums[cur] = temp; } public static void main(String[] args) { Test189 t = new Test189(); int[] arr = {1, 2, 3, 4, 5, 6}; t.rotate2(arr, 8); for (int i : arr) { System.out.print(i + " "); } } }