Skip to content

Instantly share code, notes, and snippets.

@juque
Created November 14, 2023 16:01
Show Gist options
  • Save juque/f025057cb774d9ae9511a53b37fe376a to your computer and use it in GitHub Desktop.
Save juque/f025057cb774d9ae9511a53b37fe376a to your computer and use it in GitHub Desktop.
ruby version: leetcode two sum problem
# 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]
@juque
Copy link
Author

juque commented Dec 2, 2023

Javascript version:

function twoSum(nums, target) {

  const hash = {};

  for (let i = 0; i < nums.length; i++) {

    const currentNum = nums[i];
    const complement = target - currentNum;

    if (hash.hasOwnProperty(complement)) {
      return [hash[complement], i];
    }

    hash[currentNum] = i;
  }

  return [];

}

@juque
Copy link
Author

juque commented Dec 2, 2023

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