題目地址:
https://www.lintcode.com/problem/partition-array-ii/description
給定一個數組,再給定兩個數和,要求重排數組,使得所有小於的數排在左邊,大於的數排在右邊,其餘數排在中間。要求in-place並且時間複雜度。
思路是用三個指針,其中保持,,並且,不停右移指針直到與相撞即可。代碼如下:
public class Solution {
/**
* @param nums: an integer array
* @param low: An integer
* @param high: An integer
* @return: nothing
*/
public void partition2(int[] nums, int low, int high) {
// write your code here
if (nums == null || nums.length == 0) {
return;
}
int l = -1, i = 0, r = nums.length;
while (i < r) {
// 如果當前數字小於low,那麼就將其換到左邊;
// 由於我們已經保證了A(l, i]在low與high之間,所以交換完畢後,A[i]已經在low與high之間了,所以將i也右移
// 如果當前數字大於high,則將其換到右邊;如果當前數字在low與high直接,就直接右移i
if (nums[i] < low) {
swap(nums, i++, ++l);
} else if (nums[i] > high) {
swap(nums, i, --r);
} else {
i++;
}
}
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
時間複雜度,空間。