https://www.cnblogs.com/liuzhen1995/p/6710029.html
没把空间复杂度O(1)的搬过来~~~
问题描述
有一个长度为2n的数组{a1,a2,a3,…,an,b1,b2,b3,…,bn},希望排序后变成{a1,b1,a2,b2,a3,b3,…,an,bn},请考虑有没有时间复杂度为O(n)而空间复杂度为O(1)的解法。
String[] A = {"", "a1", "a2", "a3", "a4", "a5", "b1", "b2", "b3", "b4", "b5"};
String[] temp = new String[len];
for(int i = 1;i < len;i++)
temp[(2 * i) % len] = A[i];
经过上面处理,得到:
A = {"", “b1”, “a1”, “b2”, “a2”, “b3”, “a3”, “b4”, “a4”, “b5”, “a5”};
代码:
下面算法的时间复杂度为O(n),空间复杂度为O(n)。
package com.liuzhen.practice;
public class Main {
//对于数组A第i个位置的元素都最终换到了2*i % len的位置
public void getLocationReplace(String[] A) {
int len = A.length;
String[] temp = new String[len];
for(int i = 1;i < len;i++)
temp[(2 * i) % len] = A[i];
for(int i = 1;i < len;i++)
A[i] = temp[i];
for(int i = 1;i < len;i = i + 2) {
String a1 = A[i];
A[i] = A[i + 1];
A[i + 1] = a1;
}
return;
}
public static void main(String[] args) {
Main test = new Main();
String[] A = {"", "a1", "a2", "a3", "a4", "a5", "b1", "b2", "b3", "b4", "b5"};
test.getLocationReplace(A);
for(int i = 1;i < A.length;i++)
System.out.print(A[i]+" ");
}
}