題目
給出一個(gè)整數(shù)數(shù)組 nums 和一個(gè)整數(shù) k。劃分?jǐn)?shù)組(即移動(dòng)數(shù)組 nums 中的元素),使得:
所有小于k的元素移到左邊
所有大于等于k的元素移到右邊
返回?cái)?shù)組劃分的位置,即數(shù)組中第一個(gè)位置 i,滿足 nums[i] 大于等于 k。
注意事項(xiàng)
你應(yīng)該真正的劃分?jǐn)?shù)組 nums,而不僅僅只是計(jì)算比 k 小的整數(shù)數(shù),如果數(shù)組 nums 中的所有元素都比 k 小,則返回 nums.length。
樣例
給出數(shù)組 nums = [3,2,2,1] 和 k = 2,返回 1.
分析
很簡(jiǎn)單,快速排序的partiton,兩根指針一頭一尾
代碼
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 0;
}
int left = 0, right = nums.length - 1;
while (left <= right) {
while (left <= right && nums[left] < k) {
left++;
}
while (left <= right && nums[right] >= k) {
right--;
}
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
return left;
}
}