My code is taking too long to execute. Can someone help me with optimizing this program?
Limitations:
- time: 4 seconds
- memory: 512 mb
Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static int[] a;
public static void swap(int i){
int temp=a[i];
a[i]=a[i-1];
a[i-1]=temp;
}
public static void rotate(int times,int n){
for(int j=0;j<times;j++)
for(int i=n-1;i>0;i--)
swap(i);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
a = new int[n];
int m[]=new int[q];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
for(int a0 = 0; a0 < q; a0++){
m[a0] = in.nextInt();
}
rotate(k%n,n);
for(int a0 = 0; a0 < q; a0++){
System.out.println(a[m[a0]]);
}
}
}
I think there must be some better way to swap or rotate the array.