大家好,这里是 A Fei,今天是铁人赛开赛第二天,也是连假开始前的小周末,在这先祝各位读者中秋佳节愉快!
可能有人已经注意到,标题我借用了游戏《Persona 5》的知名台词。在游戏中,主角一行人遭逢逆境,却不甘屈服命运,倾听心中「另一个我」的心声,觉醒力量後化身「怪盗团」与恶人对抗,对比正在为转职奋斗的我,心境上颇为类似,也藉此勉励自己不要轻易放弃,莫忘初衷。说个题外话,《Persona 5》的爵士风格音乐非常好听,在此也推荐给大家。
蛤?你问我说了这麽多,那跟今天的题目有什麽关联性?其实,今天的题目就叫做「
Are they the "same"?」
什麽?你说关联性很牵强,啊...让我们直接看题目:
Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.
Examples
Valid arrays
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
Invalid arrays
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]
Remarks
a or b might be [] or {} (all languages except R, Shell).
a or b might be nil or null or None or nothing (except in C++, Elixir, Haskell, PureScript, Pascal, Perl, R, Rust, Shell).
If a or b are nil (or null or None, depending on the language), the problem doesn't make sense so return false.
题目难度:6 kyu
是否有在时限内回答正确:是
题目很长,我省略了里面一部分的解释。简单来说,题目要我们比较 a、b 两个阵列,b 阵列中的每个数字,要等於 a 阵列每个数字的平方(不管排列顺序),而且 a、b 有可能是 [] 或 {}、nil 或 null。解题重点如下:
我最後的答案如下:
def comp(array1, array2)
if !array1.nil? and !array2.nil?
array2.map { |e| Math.sqrt(e) }.sort.hash == array1.map { |e| e.to_f }.sort.hash
else
false
end
end
对比评分最高的解答:
def comp(array1, array2)
return false if array1.nil? || array2.nil?
array1.map {|num| num ** 2}.sort == array2.sort
end
可以看到我程序码写得比较罗嗦外,大致上逻辑是常不多的,只是我「给敖」用了 hash 方法去比较两个阵列,其实只要用 == 就可以了。还有,为了避免有些数字开平方会有小数,我还「贴心地」用 to_f 方法将每个整数转为浮点数,好让它们可以互相比较,结果只是白操心。
好啦,修行篇第二话就写到这,我要继续赶专案进度了,各位 bye~
今天要来练习的是 C++内建的函式库 首先要先引入函式库 #include <cmath>...
先欢迎各位来到整体难度最高的领域 在听这里之前 前面的逆向组语要先学好 还有对 OS 以及计算机概论...
Change Operating Mode 攻击者修改 OT 设备的操作状态,为了要取得权限,PLC...
Zigzag Conversion Medium The string "PAYPALI...
通常一个活动,最後登场的都是主角吧?理应如此,笔者记得有一年的金马奖颁奖典礼,主办单位不知道哪根筋打...