Java旋转算法Collections.rotate
package com.example.core.mydemo.javaDemo; import java.util.ArrayList; import java.util.Collections; /** * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[4, 5, 1, 2, 3] */ public class RotateExample { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { list.add(i); } System.out.println("原始集合:" + list); Collections.rotate(list, 2); System.out.println("旋转后的集合:" + list); } } //demo2 import java.util.ArrayList; import java.util.Collections; public class RotateTest { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { list.add(i); } System.out.println("原始集合:" + list); /** * 1 * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[5, 1, 2, 3, 4] *2 * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[4, 5, 1, 2, 3] * 3 * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[3, 4, 5, 1, 2] * 4 * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[2, 3, 4, 5, 1] * 5 * 原始集合:[1, 2, 3, 4, 5] * 旋转后的集合:[1, 2, 3, 4, 5] */ Collections.rotate(list, 5); System.out.println("旋转后的集合:" + list); } }
标签:rotate,Java,ArrayList,旋转,算法,Collections From: https://www.cnblogs.com/oktokeep/p/18563460