多益网络校招
原题链接:
https://leetcode.cn/problems/rotate-array/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Solution { public void rotate(int[] nums, int k) { int n = nums.length; k = k % n; reverse(0,n - 1,nums); reverse(0,k - 1,nums); reverse(k,n - 1,nums); }
private void reverse(int start,int end,int [] q){ while(start < end){ int t = q[start]; q[start] = q[end]; q[end] = t; start++; end--; } } }
|
由于 多益网络要求的是ACM的形式 格式再附上ACM格式的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import java.util.*;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); k = k % n; int [] q = new int [n]; for (int i = 0 ; i < n ; i++){ q[i] = sc.nextInt(); }
reverse(0,n - 1,q); reverse(0, k - 1,q); reverse(k,n - 1 ,q);
Arrays.stream(q).forEach(e-> System.out.printf("%d ",e));
}
private static void reverse(int start,int end,int [] q){ while (start < end){ int t = q[start]; q[start] = q[end]; q[end] = t; start++; end--; } } }
|