We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b86951e commit 2d73efdCopy full SHA for 2d73efd
two-sum/sooooo-an.ts
@@ -1,14 +1,17 @@
1
function twoSum(nums: number[], target: number): number[] {
2
+ const visited: { [key: string]: boolean } = {};
3
for (let i = 0; i < nums.length; i++) {
- for (let j = i + 1; j < nums.length; j++) {
4
- if (nums[i] + nums[j] === target) {
5
- return [i, j];
6
- }
+ const complement = target - nums[i];
+ if (visited[complement]) {
+ const complementIdx = nums.indexOf(complement);
7
+ return [i, complementIdx];
8
}
9
+ visited[nums[i]] = true;
10
11
+ return [];
12
13
14
/**
- * runtime: 30ms / Beats 38.67%
- * memory 56.56MB / Beats 63.38%
15
+ * runtime: O(n)
16
+ * memory O(n)
17
*/
0 commit comments