我有一个练习,我必须按以下方式对数组进行排序:
例如,以下数组:
int []a={1,7,3,2,4,1,8,14}
Run Code Online (Sandbox Code Playgroud)
将会:
4 8 1 1 2 14 3 7
Run Code Online (Sandbox Code Playgroud)
组内的顺序无关紧要.
我找到了一个解决O(n)时间复杂度和O(1)空间复杂度的解决方案.
然而,它是丑陋的,并在阵列上移动3次.我想要一个更优雅的解决方案.
这是我的代码:
int ptr=a.length-1; int temp=0, i=0;
while (i<ptr){
//move 3 remained to the end
if (a[i] % 4==3){
temp=a[ptr];
a[ptr]=a[i];
a[i]=temp;
ptr--;
}
else
i++;
}
i=0;
while (i<ptr){
if (a[i]%4==2)
{
temp=a[ptr];
a[ptr]=a[i];
a[i]=temp;
ptr--;
}
else
i++;
}
i=0;
while (i<ptr){
if (a[i]%4==1)
{
temp=a[ptr];
a[ptr]=a[i];
a[i]=temp;
ptr--;
}
else
i++;
}
Run Code Online (Sandbox Code Playgroud)
重要的是要知道:
由于O(3*N)是O(N),你只需要遍历数组三次:
e % 4 == 0移到前面,沿途交换元素;e % 4 == 1移到前面,沿途交换元素;e % 4 == 2移到前面,沿途交换元素;e % 4 == 3在此之后将会结束的元素.
例:
public static void main(String args[]) {
int[] a = { 1, 7, 3, 2, 4, 1, 8, 14 , 9};
int current = 0;
for (int i = 0; i < 3; i++) {
for (int j = current; j < a.length; j++) {
if (a[j] % 4 == i) {
int b = a[j];
a[j] = a[current];
a[current] = b;
current++;
}
}
}
System.out.println(Arrays.toString(a));
}
Run Code Online (Sandbox Code Playgroud)