数组只包含0,1,2,各自的数目不一致,乱序,重新整理成类似的格式。其实就是对应位置限制成索引位和3取余数的值,i%3
,没什么太大意义,囧。比如如下的代码和输出:
public class Relocate {
public static void main(String[] args) {
int[] arr = new int[]{0,1,2,1,1,1,0,2,1,0,2,1,2,1};
System.out.println(Arrays.toString(arr));
locate(arr);
System.out.println(Arrays.toString(arr));
}
static void locate(int[] arr) {
int key;
for (int i = 0; i < arr.length; i++) {
key = i % 3;
if (arr[i] != key) {
for (int j = i; j < arr.length; j++) {
if (key == arr[j]) {
int t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
}
}
}
}
before:
[0, 1, 2, 1, 1, 1, 0, 2, 1, 0, 2, 1, 2, 1]
after:
[0, 1, 2, 0, 1, 2, 0, 1, 2, 1, 1, 2, 1, 1]