Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that: All elements < k are moved to the left. All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k. 其实就是quicksort的第一步
public class Solution {
/**
* @param nums: The integer array you should partition
* @param k: An integer
* @return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
// write your code here
int start = 0;
int end = nums.length - 1;
while(start <= end) {
while(start <= end && nums[start] < k) start++;
while(start <= end && nums[end] >= k) end--;
if(start <= end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
return start;
}
}
第二次做
public class Solution {
/**
* @param nums: The integer array you should partition
* @param k: An integer
* @return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
int p = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] < k) {
int temp = nums[p];
nums[p] = nums[i];
nums[i] = temp;
p++;
}
}
return p;
}
}