[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,緩存每個數(shù)字的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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容