[Array] 1. Two Sum

LeetCode Link

Problem Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Idea

思路就是用个Hash,缓存每个数字的index
注意这里如果无脑直接缓存的话有个小陷阱,测试用例会给类似[3,3] 6这种,于是如果一开始就更新index,那么会覆盖掉一个相同的element的index

Solution

Solution 1

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
    # because each input would have exactly one solution, so we do
    # no check the only-one-element situation
    table = Hash.new
    table[nums[0]] = 0
    nums.each_with_index do |num, index|
        unless table[target - num].nil? then
            unless index == table[target-num]
                low_index = [index, table[target-num]].min
                high_index = [index, table[target-num]].max
                return [low_index, high_index]
            end
        end
        table[num] = index # problem, same value will have hash confilct
    end
end

Solution 2: more ruby

def two_sum(numbers, target)
    hash = numbers.map.with_index.to_h
    found = numbers.find.with_index do |n, index| 
      target_index = hash[target - n] and target_index != index
    end
    [numbers.index(found), hash[target - found]].sort
end

个人感觉这个solution的缺点在于,需要把nums全部map

Review

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容