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.
Have you met this question in a real interview?
Yes
Example
If nums = [3,2,2,1]
and k=2
, a valid answer is 1
.
Note
You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
If all elements in nums are smaller than k, then return nums.length
Challenge
Can you partition the array in-place and in O(n)?
class Solution {
public:
int partitionArray(vector<int> &nums, int k) {
// write your code here
if (nums.size() == 0)
return 0;
int left = 0;
int right = nums.size()-1;
while (left < right)
{
while ((left < right) && (nums[right] >= k))
right--;
while ((left < right) && nums[left] < k)
left++;
if (left < right)
{
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
}
}
// all elements in nums are greater than or equal to k, l pointer never shift, should return r
if (left == 0 && nums[left]>=k)
return right;
// all elements in nums are smaller than k, r pointer never shift, shoud return r+1
if (right ==nums.size()-1 && nums[left] < k)
return right+1;
return right+1;
}
};