File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed
lcof/面试题21. 调整数组顺序使奇数位于偶数前面 Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments