FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_139/LeetCode_21_139.java at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_139
/
LeetCode_21_139.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (45 loc) · 1.32 KB
Breadcrumbs
algorithm
/
Week_01
/
id_139
/
LeetCode_21_139.java
Copy path
File metadata and controls
57 lines (45 loc) · 1.32 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
1
,
申请额外空间
//执行用时 : 3 ms, 在Sort Array By Parity的Java提交中击败了99.59% 的用户
//内存消耗 : 46.5 MB, 在Sort Array By Parity的Java提交中击败了68.41% 的用户
class
Solution
{
public
int
[]
sortArrayByParity
(
int
[]
A
) {
int
j
=
A
.
length
;
if
(
j
<=
1
)
return
A
;
int
[]
B
=
new
int
[
j
];
int
x
=
0
;
int
y
=
j
-
1
;
for
(
int
i
=
0
;
i
<
j
;
i
++){
//注意是i<j,而不是i<=j
if
(
A
[
i
]%
2
!=
0
){
B
[
y
] =
A
[
i
];
y
--;
}
else
{
B
[
x
] =
A
[
i
];
x
++;
}
}
return
B
;
}
}
2
,
不利用额外空间
,
前后指针
,
交换
class
Solution
{
public
int
[]
sortArrayByParity
(
int
[]
A
) {
if
(
A
==
null
||
A
.
length
==
1
)
return
A
;
int
j
=
A
.
length
-
1
;
int
i
=
0
;
while
(
i
<=
j
){
//注意不是i!=j,比如数组长度为2,会导致越界
if
(
A
[
i
]%
2
!=
0
&&
A
[
j
]%
2
==
0
){
int
temp
=
A
[
i
];
A
[
i
] =
A
[
j
];
A
[
j
] =
temp
;
i
++;
j
--;
}
else
{
if
(
A
[
i
]%
2
==
0
)
i
++;
if
(
A
[
j
]%
2
!=
0
)
j
--;
}
}
return
A
;
}
}
Back
|
FazBrowse Home
|
New Git URL