Java - Rotating array

后端 未结 14 1129

So the goal is to rotate the elements in an array right a times. As an example; if a==2, then array = {0,1,2,3,4} would become

14条回答
  •  孤城傲影
    2020-11-27 19:39

    Question : Rotate array given a specific distance . Method 1 : Turn the int array to ArrayList. Then use Collections.rotate(list,distance).

    class test1 {
        public static void main(String[] args) {
    
            int[] a = { 1, 2, 3, 4, 5, 6 };
    
            List list = Arrays.stream(a).boxed().collect(Collectors.toList());
    
            Collections.rotate(list, 3);
            System.out.println(list);//[4, 5, 6, 1, 2, 3]
    
        }// main
    }
    

提交回复
热议问题