給出一個整數數組 nums 和一個整數 k。劃分數組(即移動數組 nums 中的元素),使得:
所有小于 k 的元素移到左邊
所有大于等于 k 的元素移到右邊
返回數組劃分的位置,即數組中第一個位置 i,滿足 nums[i] 大于等于 k。
樣例
給出數組 nums = [3,2,2,1] 和 k = 2,返回 1.
代碼實現
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) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
while (left <= right && nums[left] < k) {
left++;
}
//nums[right] >= k not nums[right] > k
while(left <= right && nums[right] >= k) {
right--;
}
//if not while
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
return left;
}
}