Skip to content

Commit c1f56d8

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题21. 调整数组顺序使奇数位于偶数前面
1 parent ea636a3 commit c1f56d8

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# [面试题21. 调整数组顺序使奇数位于偶数前面](https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/)
2+
3+
## 题目描述
4+
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
5+
6+
**示例:**
7+
8+
```
9+
输入:nums = [1,2,3,4]
10+
输出:[1,3,2,4]
11+
注:[3,1,2,4] 也是正确的答案之一。
12+
```
13+
14+
**提示:**
15+
16+
- 1 <= nums.length <= 50000
17+
- 1 <= nums[i] <= 10000
18+
19+
## 解法
20+
### Python3
21+
```python
22+
class Solution:
23+
def exchange(self, nums: List[int]) -> List[int]:
24+
res = [0 for _ in range(len(nums))]
25+
p, q = 0, len(nums) - 1
26+
for e in nums:
27+
if (e & 1) == 0:
28+
res[q] = e
29+
q -= 1
30+
else:
31+
res[p] = e
32+
p += 1
33+
return res
34+
```
35+
36+
### Java
37+
```java
38+
class Solution {
39+
public int[] exchange(int[] nums) {
40+
int len = nums.length;
41+
int[] res = new int[len];
42+
int p = 0, q = len - 1;
43+
for (int e : nums) {
44+
if ((e & 1) == 0) {
45+
res[q--] = e;
46+
} else {
47+
res[p++] = e;
48+
}
49+
}
50+
return res;
51+
}
52+
}
53+
```
54+
55+
### ...
56+
```
57+
58+
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int[] exchange(int[] nums) {
3+
int len = nums.length;
4+
int[] res = new int[len];
5+
int p = 0, q = len - 1;
6+
for (int e : nums) {
7+
if ((e & 1) == 0) {
8+
res[q--] = e;
9+
} else {
10+
res[p++] = e;
11+
}
12+
}
13+
return res;
14+
}
15+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def exchange(self, nums: List[int]) -> List[int]:
3+
res = [0 for _ in range(len(nums))]
4+
p, q = 0, len(nums) - 1
5+
for e in nums:
6+
if (e & 1) == 0:
7+
res[q] = e
8+
q -= 1
9+
else:
10+
res[p] = e
11+
p += 1
12+
return res

0 commit comments

Comments
 (0)