Ruby幼幼班--Two Sum II


快忘记自己传教过哪些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

解完了,真的...


<<:  Rails幼幼班--由seeds认识Rake

>>:  [Python]专题P01─台湾春节国道预估塞车时间准不准?

LeetCode 双刀流: 236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree 今天一样...

前端工程师也能开发全端网页:挑战 30 天用 React 加上 Firebase 打造社群网站|Day8 文章主题列表

连续 30 天不中断每天上传一支教学影片,教你如何用 React 加上 Firebase 打造社群...

Day-30 终於完赛!祝各位游戏愉快!

诚如我昨天所说的、漫长的 30 天终於要在今天结束了、所以那个、这篇完全是凑数用的。 先让我插一张首...

Day 04-Terraform 也有 Backend?啥是 Terraform Backend 能吃吗?

Terraform 也有 Backend 之啥是 Terraform Backend 能吃吗? 课程...

Day 21 - Android Studio ImageView的基本使用

Day 21 - Android Studio ImageView的基本使用 昨天我们讲到了Edit...