Skip to content
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

feat: Typescript two sum solution #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all 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
54 changes: 54 additions & 0 deletions leetcode/1 - twosum/twoSum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
function twoSum(nums: number[], target: number): number[] {
const pairs: Map<number, number> = new Map();
let results: number[] = [];

nums.forEach((val, idx) => {
const found = pairs.get(target - val);

if (found !== undefined)
return results = [idx, found];

pairs.set(val, idx)

});

return results;
};

// Outras possíveis soluções
//
// function twoSum(nums: number[], target: number): number[] {
// const pairs: Map<number, number> = new Map();
// let results: number[] = [];

// for (let i = 0; i < nums.length; i++) {
// const value = nums[i];
// const found = pairs.get(target - value);

// if (found !== undefined)
// return results = [i, found];

// pairs.set(value, i)
// }

// return results;
// };
//
// function twoSum(nums: number[], target: number): number[] {
// const pairs: Map<number, number> = new Map();
// let result: number[] = [];

// for (let i = 0; i < nums.length; i++) {
// const value = nums[i];
// const found = pairs.get(target - value);

// if (found !== undefined) {
// result = [i, found];
// break;
// }

// pairs.set(value, i);
// }

// return result;
// }