iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 2
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 2

從經典 LeetCode 開始吧 - Two Sum

先說在前面
本人學 Ruby 約 2 個月左右
之前沒有寫程式背景也非相關科系
解法不見得是最好或觀看的你有更好的解法
歡迎在文章或影片下方留言交流


說到刷題,得介紹下知名網站有 LeetCodeCodewars
對於新手來說, Codewars 是個不錯選擇,能培養自信心,逐漸增加強度
想直接摧毀信心的話 LeetCode 是個好選擇(誤
LeetCode 題目有的須考量時間複雜度
對目前菜逼巴的我來說很不簡單,甚至是解不出來
看著網路解題答案時,不見得能理解答案為什麼是這樣寫
今天這題經典題 Two Sum 就是很好的例子


讓我試著以我的方式解讀題目
並試著解說給大家分享
如有資訊傳遞錯誤
歡迎不吝嗇鞭我 (是多抖 M


題目
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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

影片解題過程
Yes

初次錄影解題,超害羞
傷害到各位眼睛及耳朵
先多多包涵


解題:

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
  hash = {}
  nums.each_with_index { |number, index| hash[number] = index }
  nums.each_with_index do |number, index|
    difference = target - number
    if hash[difference] && hash[difference] != index
      return [hash[difference], index]
    end
  end
end

本文同步發布於 小菜的 Blog https://riverye.com/


上一篇
初生之犢不畏虎-參賽動機
下一篇
換刷 Codewars - Find the next perfect square!
系列文
自我挑戰 Ruby 刷題 30 天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言