Minimum Number of Operations to Reinitialize a Permutation
定义了一些操作, 求复原perm数组的操作次数.
暴力解…也没有什么简化方法.
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 |
class Solution { public int reinitializePermutation(int n) { int[] perm = new int[n]; int[] st = new int[n]; for(int i = 0; i < n; i++){ perm[i] = i; st[i] = i; } int res = 0; while(true){ int[] ary = new int[n]; for(int i = 0 ; i < n; i++) { if(i % 2 == 0) ary[i] = perm[i / 2]; else ary[i] = perm[n / 2 + (i - 1) / 2]; } perm = Arrays.copyOf(ary, n); res++; if(check(perm, st)) return res; } } public boolean check(int[] p, int[] a){ for(int i = 0 ; i < p.length; i++) { if(p[i] != a[i]) return false; } return true; } } |