Partition an unsorted integer array into three parts:
- The front part < low
- The middle part >= low & <= high
- The tail part > high
Return any of the possible solutions.
Notice
low <= high in all testcases.
Example
Given [4,3,4,1,2,3,1,2]
, and low = 2
and high = 3
.
Change to [1,1,2,3,2,3,4,4]
.
([1,1,2,2,3,3,4,4] is also a correct answer, but [1,2,1,2,3,3,4,4] is not)
可以首先将low为分级线进行排列, 然后从left > low的数据中找出以high为分界线的数据
java
public class Solution {
/*
* @param nums: an integer array
* @param low: An integer
* @param high: An integer
* @return:
*/
public void partition2(int[] nums, int low, int high) {
// write your code here
if (nums == null || nums.length == 0) {
return;
}
int left = 0, right = nums.length - 1;
while (left <= right) {
while (left <= right && nums[left] < low) {
left++;
}
while (left <= right && nums[right] >= low) {
right--;
}
if (left <= right) {
swap(nums, left, right);
left++;
right--;
}
}
right = nums.length - 1;
while (left <= right) {
while (left <= right && nums[left] <= high) {
left++;
}
while (left <= right && nums[right] > high) {
right--;
}
if (left <= right) {
swap(nums, left, right);
left++;
right--;
}
}
}
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}