题解 | #旋转数组#
旋转数组
https://www.nowcoder.com/practice/e19927a8fd5d477794dac67096862042
import java.util.*; public class Solution { /** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型一维数组 给定数组 * @return int整型一维数组 */ /** 使用三次翻转: 例: 1234567 先整体逆转 7654321 再逆转开头 6754321 再逆转结尾 6712345 */ public int[] solve (int n, int m, int[] a) { // write code here int mid = m % n - 1; reverse(a,0,n - 1); reverse(a,0,mid); reverse(a,mid+1,n-1); return a; } private void reverse(int[] a,int start , int end){ while(start < end){ swap(a,start,end); start++; end--; } } private void swap(int []a, int i ,int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } }