Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1de5ab7

Browse files
Feat: TwoSum function created with test cases (#1399)
*fix:#758 optimised armstrongNumber code* fix:#758 Average Median code optimised* feat: TwoSum function added with test cases* revert code*Fix:#758 used ternary operator to make code more optimised* Feat: TwoSum function created with test cases* Feat: TwoSum function created with test cases* Resolved comments and changes requests
1 parent86d333e commit1de5ab7

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎Maths/TwoSum.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Given an array of integers, find two numbers that add up to a specific target.
3+
*
4+
*@param {number[]} nums - The array of integers.
5+
*@param {number} target - The target sum.
6+
*@returns {number[]} - An array containing the indices of the two numbers.
7+
*
8+
*@example
9+
* const nums = [2, 7, 11, 15];
10+
* const target = 9;
11+
* const result = twoSum(nums, target);
12+
* // The function should return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9.
13+
*/
14+
15+
constTwoSum=(nums,target)=>{
16+
constnumIndicesMap=newMap()
17+
for(leti=0;i<nums.length;i++){
18+
constcomplement=target-nums[i]
19+
if(numIndicesMap.has(complement))return[numIndicesMap.get(complement),i]
20+
numIndicesMap.set(nums[i],i)
21+
}
22+
return[]
23+
}
24+
export{TwoSum}

‎Maths/test/TwoSum.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import{TwoSum}from'../TwoSum.js'
2+
describe('Two Sum',()=>{
3+
consttestCasesWithoutSolution=[
4+
[[8],8],
5+
[[3,3,3,3],19]
6+
]
7+
consttestCasesWithSolution=[
8+
[[2,7,11,15],9,[0,1]],
9+
[[15,2,11,7],13,[1,2]],
10+
[[2,7,11,15],17,[0,3]],
11+
[[7,15,11,2],18,[0,2]],
12+
[[2,7,11,15],26,[2,3]]
13+
]
14+
15+
test.each(testCasesWithoutSolution)(
16+
'Should return an empty array if there is no solution',
17+
(nums,target)=>{
18+
expect(TwoSum(nums,target)).toEqual([])
19+
}
20+
)
21+
22+
test.each(testCasesWithSolution)(
23+
'Should return the indices of two numbers that add up to the target',
24+
(nums,target,expected)=>{
25+
expect(TwoSum(nums,target)).toEqual(expected)
26+
}
27+
)
28+
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp