一个数组A中存有 n 个整数,在不允许使用另外数组的前提下,将每个整数循环向右移 M( M >=0)个位置

题目:
描述
一个数组A中存有 n 个整数,在不允许使用另外数组的前提下,将每个整数循环向右移 M( M >=0)个位置,即将A中的数据由(A0 A1 ……AN-1 )变换为(AN-M …… AN-1 A0 A1 ……AN-M-1 )(最后 M 个数循环移至最前面的 M 个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

描述
一个数组A中存有 n 个整数,在不允许使用另外数组的前提下,将每个整数循环向右移 M( M >=0)个位置,即将A中的数据由(A0 A1 ……AN-1 )变换为(AN-M …… AN-1 A0 A1 ……AN-M-1 )(最后 M 个数循环移至最前面的 M 个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

示例1
输入:
6,2,[1,2,3,4,5,6]

返回值:
[5,6,1,2,3,4]

即1向右移动2位置,2向右移动2位置,等等;

题目主要信息:
一个长度为n的数组,将数组整体循环右移m个位置(m可能大于n)
循环右移即最后m个元素放在数组最前面,前n−m个元素依次后移
不能使用额外的数组空间

使用集合:

package test3;

import java.util.LinkedList;
import java.util.List;

public class Arr7 {
    public static void main(String[] args) {
        Arr7 arr7 = new Arr7();
        int[] test = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13};
        int[] solve = arr7.solve(13, 26, test);
    }
    public int[] solve (int n, int m, int[] a) {
       //取余,因为每次长度为n的旋转数组相当于没有变化
        m=m%n;
        LinkedList<Integer> list = new LinkedList<>();

        for (int i = 0; i < a.length; i++) {
            list.add((a[i]));
        }

        List<Integer> list1 = list.subList(0, n - m);
        System.out.println(list1);
        List<Integer> list2 = list.subList(n - m,list.size());
        System.out.println(list2);
        LinkedList<Integer> res = new LinkedList<>();
        res.addAll(list2);
        res.addAll(list1);
        System.out.println(res);
        for (int i = 0; i <res.size() ; i++) {
            a[i]= res.get(i);
        }
        return a;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38568503/article/details/128399038