FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Maths/TwoSum.js at master · ArduinoAficionado/JavaScript · GitHub
ArduinoAficionado
/
JavaScript
Public
forked from
TheAlgorithms/JavaScript
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
JavaScript
/
Maths
/
TwoSum.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
24 lines (23 loc) · 755 Bytes
Breadcrumbs
JavaScript
/
Maths
/
TwoSum.js
Copy path
File metadata and controls
24 lines (23 loc) · 755 Bytes
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
/**
* Given an array of integers, find two numbers that add up to a specific target.
*
*
@param
{
number[]
} nums - The array of integers.
*
@param
{
number
} target - The target sum.
*
@returns
{
number[]
} - An array containing the indices of the two numbers.
*
*
@example
* const nums = [2, 7, 11, 15];
* const target = 9;
* const result = twoSum(nums, target);
* // The function should return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9.
*/
const
TwoSum
=
(
nums
,
target
)
=>
{
const
numIndicesMap
=
new
Map
(
)
for
(
let
i
=
0
;
i
<
nums
.
length
;
i
++
)
{
const
complement
=
target
-
nums
[
i
]
if
(
numIndicesMap
.
has
(
complement
)
)
return
[
numIndicesMap
.
get
(
complement
)
,
i
]
numIndicesMap
.
set
(
nums
[
i
]
,
i
)
}
return
[
]
}
export
{
TwoSum
}
Back
|
FazBrowse Home
|
New Git URL