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.
Note
思路:和Sort Color一致,先左右按照要求分好,再遍历新数组,返回第一个比K大的值。
You should do really partition in array "nums" instead of just counting the numbers of integers smaller than k.
public class Solution {
/**
*@param nums: The integer array you should partition
*@param k: As description
*return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
//write your code here
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
int i = 0;
while (i <= right) {
if (nums[i] < k) {
swap(nums, i, left);
left++;
i++;
} else {
swap(nums, i, right);
right--;
}
}
for (int j = 0; j < nums.length; j++) {
if (nums[j] >= k) {
return j;
}
}
return -1;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}