Skip to content

Commit 345e956

Browse files
committed
two sum solution
1 parent 6690735 commit 345e956

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

โ€Žtwo-sum/yeeZinu.jsโ€Ž

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
/*
8+
๋‘ ์ˆ˜ ๋”ํ•˜๊ธฐ
9+
nums: ์ˆซ์ž ๋ฐฐ์—ด
10+
target: ๋ชฉํ‘œ ์ˆซ์ž
11+
12+
target ์ˆซ์ž์— ๋งž๊ฒŒ nums ๋ฐฐ์—ด์ค‘ 2๊ฐœ๋ฅผ ๋”ํ•จ.
13+
return์€ ๋”ํ•œ ๋‘ ์ˆ˜์˜ index
14+
- for i in nums -> target - i ๊ฐ’์ด ๋ฐฐ์—ด๋‚ด์— ์žˆ๋Š”์ง€ ์ฐพ๊ธฐ
15+
*/
16+
var twoSum = function (nums, target) {
17+
let indexArray = []; // ๋‹ต์„ ์ €์žฅํ•  ๋ฐฐ์—ด
18+
for (let i = 0; i < nums.length; i++) {
19+
let tNum = nums.lastIndexOf(target - nums[i]); // ๋ฐฐ์—ด๋‚ด์— target - nums[i] ์ฐพ๊ธฐ
20+
if (i === tNum) { // ๊ฐ™์€ ์ˆ˜ ์‚ฌ์šฉ ๋ฐฉ์ง€
21+
22+
}
23+
else if (tNum > 0 && indexArray.lastIndexOf(i) === -1) { // ๋ฐฐ์—ด๋‚ด์— ์›ํ•˜๋Š” ๊ฐ’์ด ์žˆ๋‹ค๋ฉด
24+
indexArray.push(i);
25+
indexArray.push(tNum);
26+
break;
27+
}
28+
}
29+
return indexArray;
30+
};

0 commit comments

Comments
ย (0)