iT邦幫忙

1

Ruby幼幼班--Two Sum II

Yes
快忘記自己傳教過哪些K-pop了....


Two Sum II

題目連結:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
題目重點:sorted。
然後觀察,其實就是陣列值各+1...??

複習一下each_with_index這個語法

2.7.3 :005 > hash = {}
 => {} 
2.7.3 :007 > [2,7,11,15].each_with_index {|num, index| hash[num] = index}
 => [2, 7, 11, 15] 
2.7.3 :008 > hash
 => {2=>0, 7=>1, 11=>2, 15=>3} 

007那行嘗試翻一下白話文,將陣列中每個值,依照由0開始依序排列,回傳一個新的雜湊出來。

先回到Two Sum(題號:001, 人生的第一個難題)
題目連結:https://leetcode.com/problems/two-sum/

new_hash = {}
nums.each_with_index do |num, index| 
  return [new_hash[num], index] if new_hash.has_key?(num)
  new_hash[target - num] = index
end

那時做出的新雜湊如下(由例子1看)

2.7.3 :011 > hash = {}
 => {} 
2.7.3 :012 > [2,7,11,15].each_with_index {|num, index| hash[9 - num] = index}
 => [2, 7, 11, 15] 
2.7.3 :013 > hash
 => {7=>0, 2=>1, -2=>2, -6=>3} 

為的是查表,看看我要找的key有沒有,位置在哪。
但相對的,其實題目一定符合陣列內含有target拆開的兩個值。
所以答案其實可以改寫如下


def two_sum(nums, target)
  hash = {}    
  nums.each_with_index do |num, i|
    return [hash[target - num] , i]  if hash[target - num]
    hash[num] = i
  end
  #new_hash = {}
  #nums.each_with_index do |num, index| 
    #return [new_hash[num], index] if new_hash.has_key?(num)
    #new_hash[target - num] = index
  #end
end

#再放一次舊的,老話,哪個看得懂,哪個好。

所以Two Sum II 的ans

def two_sum(numbers, target)
  hash = {}    
  numbers.each_with_index do |num, i|
    return [hash[target - num] +1 , i + 1]  if hash[target - num]
    hash[num] = i
  end
end

解完了,真的...


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言