不交换数组,逐个暴力插入
旋转数组
https://www.nowcoder.com/practice/e19927a8fd5d477794dac67096862042
import java.util.*; public class Solution { /** 从第0个位置开始,将第0个位置的值移入第 (0+m)%n 个位置,需要提前保存下一个位置的值,做 n 次操作。 问题一:当 m 是奇数,可以直接按总思路处理。 问题二:当 m 是偶数,需要操作两次,因为会 nextIndex 会循环会第一个位置。 */ public int[] solve (int n, int m, int[] a) { // write code here if(a.length <= 1) return a; if(m > n) m = m % n; if(m % 2 == 0) { // 两次 insertNext(0, n/2, a, n, m); insertNext(1, n/2, a, n, m); } else { // 一次 insertNext(0, n, a, n, m); } return a; } public void insertNext(int curIndex, int count, int[] a, int n, int m) { int curValue = a[curIndex]; int nextIndex = (curIndex + m) % n; int nextValue = a[nextIndex]; for(int i=0; i<count; i++) { a[nextIndex] = curValue; curIndex = nextIndex; curValue = nextValue; nextIndex = (curIndex + m) % n; nextValue = a[nextIndex]; } } }