# #31 Partition Array

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.

##### Notice

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

Example

If nums = [3,2,2,1] and k=2, a valid answer is 1.

Challenge

Can you partition the array in-place and in O(n)?

Mycode（AC = 13ms）：

class Solution {
public:
int partitionArray(vector<int> &nums, int k) {
// write your code here
if (nums.size() == 0) return 0;

int l = 0, r = nums.size() - 1;
for (int i = 0; i <= r; i++) {
// swap left and index if nums[i] < k
if (nums[i] < k) {
swap(nums, i, l);
l++;
}
// swap right and index if nums[i] < k
else {
swap(nums, i, r);
// it is possible that the original
// nums[r] is smaller than k, in that
// case, should do another swap between
// l and old i
if (nums[i] < k) i--;
r--;
}
}

return l;
}

void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};

#### Array Partition

2018-06-19 10:27:18

#### Partition Array

2015-11-29 16:26:38

#### python--leetcode561. Array Partition I

2017-09-22 17:12:29

#### 【LeetCode】Array Partition I 解题报告

2017-05-08 14:41:23

#### LeetCode 561. Array Partition I

2017-04-24 09:36:20

#### leetcode#561 Array Partition I

2017-04-25 14:59:38

#### 代码面试题：Partition Array

2014-09-11 02:01:39

#### leetcode-561(Array Partition I)

2017-06-02 10:58:27

#### LeetCode.561 Array Partition I

2017-10-25 11:02:33

#### Leetcode561. Array Partition I

2017-08-11 09:36:17