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

Commit 44e2a46

Browse files
committed
Add alternative solution
1 parent 676f1d0 commit 44e2a46

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

‎README.md

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1179,15 +1179,24 @@ console.log(twoSum([3, 2, 4], 6)); // [1, 2]
11791179

11801180
```js
11811181
const twoSum = (nums, target) => {
1182-
const map = new Map();
1183-
1184-
for (let i = 0; i < nums.length; i++) {
1185-
const otherIndex = map.get(target - nums[i]);
1186-
if (typeof otherIndex !== 'undefined') {
1187-
return [otherIndex, i];
1182+
const len = nums.length;
1183+
for (let i = 0; i < len; i++) {
1184+
const j = nums.lastIndexOf(target - nums[i]);
1185+
if (j > i) {
1186+
return [i, j];
11881187
}
1189-
map.set(nums[i], i);
11901188
}
1189+
1190+
// Alternative solution using Map
1191+
// const map = new Map();
1192+
1193+
// for (let i = 0; i < nums.length; i++) {
1194+
// const otherIndex = map.get(target - nums[i]);
1195+
// if (typeof otherIndex !== 'undefined') {
1196+
// return [otherIndex, i];
1197+
// }
1198+
// map.set(nums[i], i);
1199+
// }
11911200
};
11921201
```
11931202

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /