給定一個整數數組找到將數組劃分爲兩個高數和低數的索引。例如[5,-1,3,8,6],索引3將把數組分割爲[5,-1,3]和[8,6],第二個分區中的所有數字都大於第一個。該解決方案必須在O(n)中工作。請建議如果這是正確的,並達到O(n)的複雜性。Parition an Array
private int calculateWinters(int[] a) {
System.out.println(partition(a, 0, a.length - 1));
return partition(a, 0, a.length - 1);
}
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low; // index of smaller element
int count = 0;
for (int j = low; j <= high; j++) {
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot) {
i++;
i += count;
count = 0;
} else {
int temp = arr[j];
arr[j] = pivot;
pivot = temp;
count++;
}
}
return i;
}
它達到O(n)的複雜性,但它似乎並沒有做你想做的。在您的'else'部分,您將交換數組中的條目 - 這不在要求的描述中。 – OldCurmudgeon
那麼.. *它是正確的嗎?如果你甚至無法驗證自己的要求,你在問什麼?這是*最少*你應該能夠帶着問題來到這裏。 –
@OldCurmudgeon你可以提出一個更好的解決方案,不需要交換,因爲我只是索引。 –