Skip to content

add: two sum #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions LeetcodeProblems/Algorithms/2Sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
2 Sum
https://leetcode.com/problems/two-sum/

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]

*/

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let map ={};
for(let i=0;i<nums.length;i++){
const sum = target-nums[i];
if(map[parseInt(sum)] != void 0){
return [map[sum], i];
} else{
map[nums[i]] = i;
}
}
};

module.exports.twoSum = twoSum;
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
| [Majority Element](/LeetcodeProblems/Algorithms/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ |
| [Two Sum](/LeetcodeProblems/Algorithms/2Sum.js) | Easy | https://leetcode.com/problems/two-sum/ |
| [Tic Tac Toe ](/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js) | | |
| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | |
| [Deletion Distance](/LeetcodeProblems/Algorithms/Deletion_Distance.js) | | |
Expand Down