Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
李楚霏
/
leetCode_Solution_Record
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
0349e630
authored
Aug 21, 2020
by
李楚霏
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
8/21 两数之和
parent
da7df576
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
38 additions
and
0 deletions
+38
-0
towSum.cpp
+38
-0
No files found.
towSum.cpp
0 → 100644
View file @
0349e630
/**
* 一次哈希遍历
* 解题思路:数值作为map的键,下标作为map的值;
* 每次遍历时,如果target-nums[i]在map中能找到值,
* 说明target的两个数已经找到,就返回
*/
#include <iostream>
#include<vector>
#include<map>
using
namespace
std
;
class
Solution
{
public
:
vector
<
int
>
twoSum
(
vector
<
int
>&
nums
,
int
target
)
{
vector
<
int
>
res
;
map
<
int
,
int
>
hashmap
;
for
(
int
i
=
0
;
i
<
nums
.
size
();
i
++
)
{
if
(
hashmap
[
target
-
nums
[
i
]]
&&
hashmap
[
target
-
nums
[
i
]]
!=
i
+
1
)
{
res
.
push_back
(
i
);
res
.
push_back
(
hashmap
[
target
-
nums
[
i
]]
-
1
);
return
res
;
}
//不让hash的下标为负
hashmap
[
nums
[
i
]]
=
i
+
1
;
}
return
res
;
}
};
int
main
()
{
Solution
s
;
vector
<
int
>
test
=
{
-
2
,
11
,
4
,
15
,
7
,
5
};
for
(
int
i
=
0
;
i
<
s
.
twoSum
(
test
,
9
).
size
();
i
++
)
{
cout
<<
s
.
twoSum
(
test
,
9
)[
i
]
<<
endl
;
}
return
0
;
}
\ No newline at end of file
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