Created
November 14, 2023 16:01
-
-
Save juque/f025057cb774d9ae9511a53b37fe376a to your computer and use it in GitHub Desktop.
ruby version: leetcode two sum problem
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
# Ruby version leetcode problem two_sum | |
def two_sum(nums, target) | |
hash = {} | |
nums.each.with_index do |k, i| | |
return [ hash[target - k], i ] if hash.key?(target - k) | |
hash[k] = i | |
end | |
end | |
data = [2,1,5,4,9,6] | |
target = 10 | |
result = two_sum(data, target) | |
puts result.inspect # [1, 4] |
Javascript v2: Using reduce
function twoSum (nums, target) {
const hash = {};
return nums.reduce((acc, currentNum, i) => {
const complement = target - currentNum;
if (hash.hasOwnProperty(complement)) {
return [hash[complement], i];
}
hash[currentNum] = i;
return acc;
}, []);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Javascript version: