Skip to content

Commit 4dd8638

Browse files
committed
[en] Add Partition Array by Odd and Even
1 parent 614a691 commit 4dd8638

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Partition Array by Odd and Even
2+
3+
## Question
4+
5+
- lintcode: [(373) Partition Array by Odd and Even](http://www.lintcode.com/en/problem/partition-array-by-odd-and-even/)
6+
- [Segregate Even and Odd numbers - GeeksforGeeks](http://www.geeksforgeeks.org/segregate-even-and-odd-numbers/)
7+
8+
```
9+
Partition an integers array into odd number first and even number second.
10+
11+
Example
12+
Given [1, 2, 3, 4], return [1, 3, 2, 4]
13+
14+
Challenge
15+
Do it in-place.
16+
```
17+
18+
## Solution
19+
20+
Use **two pointers** to keep the odd before the even, and swap when necessary.
21+
22+
### Java
23+
24+
```java
25+
public class Solution {
26+
/**
27+
* @param nums: an array of integers
28+
* @return: nothing
29+
*/
30+
public void partitionArray(int[] nums) {
31+
if (nums == null) return;
32+
33+
int left = 0, right = nums.length - 1;
34+
while (left < right) {
35+
// odd number
36+
while (left < right && nums[left] % 2 != 0) {
37+
left++;
38+
}
39+
// even number
40+
while (left < right && nums[right] % 2 == 0) {
41+
right--;
42+
}
43+
// swap
44+
if (left < right) {
45+
int temp = nums[left];
46+
nums[left] = nums[right];
47+
nums[right] = temp;
48+
}
49+
}
50+
}
51+
}
52+
```
53+
54+
### C++
55+
56+
```c++
57+
void partitionArray(vector<int> &nums) {
58+
if (nums.empty()) return;
59+
60+
int i=0, j=nums.size()-1;
61+
while (i<j) {
62+
while (i<j && nums[i]%2!=0) i++;
63+
while (i<j && nums[j]%2==0) j--;
64+
if (i != j) swap(nums[i], nums[j]);
65+
}
66+
}
67+
```
68+
69+
### Src Code Analysis
70+
71+
Be careful not to forget `left < right` in while loop condition.
72+
73+
### Complexity
74+
75+
To traverse the array, time complexity is $$O(n)$$. And maintain two pointers mean $$O(1)$$ space complexity.

0 commit comments

Comments
 (0)