Last active
August 4, 2016 18:58
-
-
Save jafow/7bb8e0863b44b3f2ecc76ffac14388ac to your computer and use it in GitHub Desktop.
targetSum.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define a function 'targetSum' that takes 2 arguments, an array and a target number, and returns a boolean for whether or not | |
//2 values in the array sum up to the target number | |
// ex: targetSum([1, 3, 5, 0, 6, 4, 2], 11) // => 11 | |
// brute force | |
function targetSum (arr, target) { | |
for (var i = 0; i < arr.length; i++) { | |
for (var j = i + 1; j < arr.length; j++) { | |
if (arr[i] + arr[j] === target) return true | |
} | |
} | |
} | |
// O(n) time and space, use an object | |
const target = (arr, target) => { | |
const table = {} | |
let hasTarget = false | |
arr.forEach((n) => table[target - n] | |
? hasTarget = true | |
: table[n] = 1 | |
) | |
return hasTarget | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment