Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19]
方法 1.导航阵列。
如果a [i]!= -1且元素a [i]不在其正确位置(i!= A [i]),则将其置于正确位置,但有两个条件:
(i).A [i]是空的,意味着A [i] = -1,然后只是把A [i] = i。
(ii).OR A [i]不是空的,意味着A [i] = x,则int y = x put A [i] = i。现在,我们需要将y放在正确的位置,重复步骤3。
以下解决方案的时间复杂度是多少?
public static int[] fix(int[] A) {
for (int i = 0, x = A[i]; i < A.length; i++) {
if (x == -1 || x == i)
continue;
// check if desired place is not vacant
while (A[x] != -1 && A[x] != x) {
int y = A[x]; // store the value from desired place
A[x] = x; // place the x to its correct position
x = y; // now y will become x, now search the place for x
}
A[x] = x; // place the x to its correct position
// check if while loop hasn't set the correct value at A[i]
if (A[i] != i)
A[i] = -1; // if not then put -1 at the vacated place
}
return A;
}
答案 0 :(得分:1)
我可以为您提供两种算法。
第一个:使用额外数组,时间复杂度为O(n)
,O(n)
额外内存
public static int[] fix(int[] arr) {
int[] res = new int[arr.length];
Arrays.fill(res, -1);
for (int i = 0; i < arr.length; i++)
if (arr[i] != -1)
res[arr[i]] = arr[i];
return res;
}
第二个:到位,在最坏的情况下,时间复杂度为O(n^2)
,在平均情况下为O(n)
,没有额外的内存
public static int[] fix(int[] arr) {
int i;
while ((i = findIncorrectPosition(arr)) >= 0) {
while (arr[i] != -1 && arr[i] != i) {
swap(arr, i, arr[i]);
}
}
return arr;
}
...加上两种私人支持方式:
private static int findIncorrectPosition(int[] arr) {
for (int i = 0; i < arr.length; i++)
if (arr[i] != -1 && arr[i] != i)
return i;
return -1;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
答案 1 :(得分:0)
f(n) = O(n) 使用交换方法#Swift
for i in stride(from: 0, to: array.count, by: 1){
if(array[i] >= 0 && array[i] != i){
let ele = array[array[i]]
array[array[i]] = array[i]
array[i] = ele
}
}
for k in stride(from: 0, to: array.count, by:1 ){
print(" ",array[k])
}