给出一个整数数组 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: An integer
* @return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
// write your code here
int i = 0, j = nums.length-1;
while (i < j) {
while (i < nums.length && nums[i] < k) {
i++;
}
while (j >= 0 && nums[j] >= k) {
j--;
}
if (i > j) {
break;
}
if (i > nums.length) {
break;
}
if (j < 0) {
break;
}
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return i;
}
}