Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Solution {
- public static void main(String[] args) {
- //initializing regular code...
- Scanner s = new Scanner(System.in);
- int n = s.nextInt();
- int d = s.nextInt();
- int[] arr = new int[n];
- for(int i = 0; i < n; i++)
- arr[i] = s.nextInt();
- //for optimal solution, if n==d or d is multiple of n then we do nothing.
- //example: move array of 5 elements, 5 place to the left. We do nothing.
- //Therefor we remove from d the multiple of n.
- //if d is not multiple of n
- if(d%n != 0) {
- if(d > n) {
- while(d>n) {
- //here we remove n from d. (But we need to check when to stop.)
- if(d < n)
- break;
- d -= n;
- }
- }
- /*
- after all the work we got d that is 100% less than n. which is good, so we don't need to do mutliple
- rotations to get to the same result.
- My optimal solution:
- Create new list of size n. Add all elements from arr[] to new list, starting from index d (included)
- up to index arr.length (which is n) . That way only the "rotating elements from left to right" will
- be added later, and the "not rotating elements from left to right" are added immidietly, without checking.
- */
- int[] newArr = new int[n];
- for(int i = 0; i < (n - d); i++)
- newArr[i] = arr[d+i];
- //we done adding all "non rotating elements"
- //now append all "moving elements"
- //they are in arr[] from index (include) 0 to index (include) d-1 .
- for(int i = 0; i < d; i++)
- newArr[n-d+i] = arr[i];
- //and we done!
- //print result
- for(int i = 0; i < n; i++)
- System.out.print(newArr[i] + " ");
- }
- else
- //print result
- for(int i = 0; i < n; i++)
- System.out.print(arr[i] + " ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement