思路
- 这道题没什么考察点,主要是要注意两个for循环,一定要加上
pos1 < pos2
防止越界。同时,注意题中最后的要求,如果都比k小,则返回数组的长度。
代码
public static int partitionArray(int[] nums, int k) {
// write your code here
int pos1 = 0;
int pos2 = nums.length-1;
int temp = 0;
while (pos1 < pos2) {
for (;nums[pos1] < k && pos1 < pos2; pos1++);
for (; nums[pos2] >= k && pos1 < pos2; pos2--);
temp = nums[pos1];
nums[pos1] = nums[pos2];
nums[pos2] = temp;
}
if (pos1 == nums.length-1) {
pos1 = nums.length;
}
return pos1;
}