Skip to content

Instantly share code, notes, and snippets.

@ytaminE
Last active November 30, 2017 02:14
Show Gist options
  • Select an option

  • Save ytaminE/8d37f8cfffb63c112b10463bf9a4e0c7 to your computer and use it in GitHub Desktop.

Select an option

Save ytaminE/8d37f8cfffb63c112b10463bf9a4e0c7 to your computer and use it in GitHub Desktop.
Solution for TwoSum

Solution for TwoSum

Input: nums are [2, 7, 11, 15] and target is 9

[2,7,11,15,9]

Result:

[0,1]

Python

def TwoSum(nums):
    target = nums[-1]
    nums = nums[0:-1]
    map = {}
    for i in range(len(nums)):
        if nums[i] not in map:
            map[target - nums[i]] = i
        else:
            return map[nums[i]], i
    return "No result found"

Ruby

class Solution
    def TwoSum(nums)
      target = nums[nums.size-1]
      numbers_hash = {}
      nums.each_with_index do |number, index|
        numbers_hash[index] = number
        hash_key = ((numbers_hash.select { |k,v| v == (target - number) }.keys) - [index])
        hash_key.empty? ? false : (return [hash_key, index].flatten)
      end
      return "Couldn't find target value"
    end
end

JavaScript

module.exports={
    TwoSum:function(){
        var nums = arguments[0];
        var target = nums[nums.length-1];
        nums = nums.slice(0,nums.length-1)
        var saved={}
        var result=[]
        for(i=0; i< nums.length; i++){
            if(saved.hasOwnProperty(nums[i])){
                result[0] = saved[nums[i]];
                result[1] = i;
                return result
              }
        saved[target - nums[i]] = i
        }
        return "No result found";
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment