Saved Bookmarks
| 1. |
How do you rotate an array? |
|
Answer» You will be given an input number N and N numbers following it as the input. You are ALSO given an integer K which represents how many times you have to rotate the array. Rotate the array K values to the right if K is positive and K values to the left if K is negative. If K=0, do not rotate the array. The figure shows how the rotating array will look if k=2. Approach:
Code: import java.io.*;import java.util.*;public class Main { public static void display(int[] arr) { StringBuilder sb = new StringBuilder();for (int val : arr) { sb.append(val + " "); } System.out.println(sb); } public static void reverse(int[] arr, int li, int ri) { while (li < ri) { int t = arr[li]; arr[li] = arr[ri]; arr[ri] = t; li++; ri--; } } public static void rotate(int[] arr, int k) { k = k % arr.length; if (k < 0) { k += arr.length; } reverse(arr, 0, arr.length - k - 1); reverse(arr, arr.length - k, arr.length - 1); reverse(arr, 0, arr.length - 1); } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(br.readLine()); } int k = Integer.parseInt(br.readLine()); rotate(arr, k); display(arr); } |
|