Skip to content

Instantly share code, notes, and snippets.

@dynamicy
Created May 20, 2022 04:59
Show Gist options
  • Save dynamicy/236c29f84e001bedd769262aaffa7357 to your computer and use it in GitHub Desktop.
Save dynamicy/236c29f84e001bedd769262aaffa7357 to your computer and use it in GitHub Desktop.
1. Two Sum
Two Sum:
https://leetcode.com/problems/two-sum/submissions/
// O(n^2)
for(let i = 0; i < array.length; i++) {
for(let j = 1; j < array.length; j++) {
if(array[i] + array[j] === target) {
console.log('i: ' + i + ' j: ' + j);
}
}
}
// O(n)
function twoSum(nums: number[], target: number): number[] {
const map: Map<number, number> = new Map();
for (let i=0; i<nums.length; i++) {
const current = nums[i];
const remain = map.get(target - current);
if (remain !== undefined) {
return [i, remain];
}
map.set(current, i);
}
return [];
};
// [2,5,5,11]
// 10
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
const array = [2,7,11,15];
// const array = [3,2,4];
// const array = [3,3];
// const array = [2,5,5,11];
const target = 9;
// const target = 6;
// const target = 10;
const answer = twoSum(array, target);
console.log(answer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment