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 inums[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
Tags Expand
Can you partition the array in-place and in O(n)?
Just like partition function for quick sort.
Use two pointers left and right to compare with k. If left < k, left ++; If right > k, right --. When left and right stop forwarding, exchange values. When left > right, all elements have been partitioned.
Time: O(n)
Space: O(1)
class Solution { public: int partitionArray(vector<int> &nums, int k) { // write your code here int left = 0; int right = nums.size() - 1; while(left < right){ while(nums[left] < k && left < nums.size()) left++; while(nums[right] >= k && right >= 0) right--; if(left < right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } } //return left; return right + 1; } };
http://www.code123.cc/docs/leetcode-notes/integer_array/partition_array.html
Lintcode second:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public: int partitionArray(vector<int> &nums, int k) { int left = 0; int right = nums.size() - 1; while(left < right){ while(nums[left] < k && left < nums.size()){ left++; } while(nums[right] >= k && right >= 0){ right--; } if(left < right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } return left; } }; |
没有评论:
发表评论