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 06c9f0a

Browse files
committed
Two solutions for two sum problem
1 parent 82efcb0 commit 06c9f0a

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

‎README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ An algorithm is a series of step-by-step instructions that describe how to do so
44

55
To write an effective algorithm, it helps to break a problem down into smaller parts and think carefully about how to solve each part with code.
66

7-
This repository contains JavaScript based examples that will teach you the fundamentals of algorithmic thinking by writing functions that do everything from converting temperatures to handling complex 2D arrays.
7+
This repository contains JavaScript algorithm examples and solutions from Leetcode.
88

99
All of these examples are from FreeCodeCamp's [problemset](https://leetcode.com/problemset/all/).
1010

@@ -42,3 +42,32 @@ Output: [0, 1];
4242
- -109 <= nums[i] <= 109
4343
- -109 <= target <= 109
4444
- **Only one valid answer exists.**
45+
46+
### Solution 1
47+
48+
```js
49+
var twoSum = function (nums, target) {
50+
for (let i = 0; i < nums.length; i++) {
51+
for (let j = i + 1; j < nums.length; j++) {
52+
if (nums[i] + nums[j] === target) {
53+
return [i, j];
54+
}
55+
}
56+
}
57+
};
58+
```
59+
60+
### Solution 2
61+
62+
```js
63+
var twoSum = function (nums, target) {
64+
let numsStorage = {};
65+
for (let i = 0; i < nums.length; i++) {
66+
if (numsStorage[nums[i]] === undefined) {
67+
numsStorage[target - nums[i]] = i;
68+
} else {
69+
return [numsStorage[nums[i]], i];
70+
}
71+
}
72+
};
73+
```

0 commit comments

Comments
(0)

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