Skip to content

Commit

Permalink
Remove nested loops and replace with a single loop
Browse files Browse the repository at this point in the history
  • Loading branch information
yinxoxo committed Jun 28, 2024
1 parent c8441a6 commit 08e13fa
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions Week2/Assignment5.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
function twoSum(nums, target) {
// your code here

//儲存數字及index
let numList = {};

for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
let need = target - nums[i];

if (numList.hasOwnProperty(need)) {
return [numList[need], i];
}
numList[nums[i]] = i;
}
}

/*
For example:
twoSum([2, 7, 11, 15], 9);
Expand Down

0 comments on commit 08e13fa

Please sign in to comment.