Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
yaozc
ProjectLeet
Commits
9af8a9de
Commit
9af8a9de
authored
Jan 26, 2019
by
yaozc
Browse files
27 solved
parent
d819cdd6
Changes
1
Hide whitespace changes
Inline
Side-by-side
code.cpp
View file @
9af8a9de
...
...
@@ -44,3 +44,30 @@ int removeDuplicates(vector<int>& nums) {
}
return
++
left
;
}
//27 Remove Element
//solution1:使用vector中的erase;需要注意,erase一个iterator后,该指针会成为野指针,不能直接++,所以要让iterator等于erase后返回的新指针(该指针指向vector中后一个element)
int
removeElement
(
vector
<
int
>&
nums
,
int
val
)
{
for
(
auto
i
=
nums
.
begin
();
i
!=
nums
.
end
();){
if
(
*
i
==
val
){
i
=
nums
.
erase
(
i
);
}
else
{
i
++
;
}
}
return
nums
.
size
();
}
//solution2:将等于val的element移到vector最后,注意(1)i应该小于nums.size()-counter, (2)swap后应该将i--,这样才不会漏检查swap后的当前element。
int
removeElement
(
vector
<
int
>&
nums
,
int
val
)
{
int
counter
=
0
;
for
(
int
i
=
0
;
i
<
nums
.
size
()
-
counter
;
i
++
){
if
(
nums
[
i
]
==
val
){
swap
(
nums
[
i
],
nums
[
nums
.
size
()
-
counter
-
1
]);
counter
++
;
i
--
;
}
}
return
nums
.
size
()
-
counter
;
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment