黑魔法集合....
题目连结:https://leetcode.com/problems/single-number/
题目提示:阵列中,一个元素最多2个,其中一个只有一次。
整理
# @param {Integer[]} nums
# @return {Integer}
def single_number(nums)
end
p single_number([2,2,1]) #=> 1
p single_number([4,1,2,1,2]) #=> 4
p single_number([1]) #=> 1
其实Ruby查表法很方便,枚举习惯後。
def single_number(nums)
#变成hash, key == 数值, value == 个数
#挑出个数1的key(value是1的)
end
def single_number(nums)
#变成hash, key == 数值, value == 个数
new_hash = nums.tally
#挑出个数1的key(value是1的)
new_hash.key(1)
end
#tally:Tallies the collection, i.e., counts the occurrences of each element. Returns a hash with the elements of the collection as keys and the corresponding counts as values.
2.7.3 :001 > ["a", "a", "b", "c", "c", "c"].tally
=> {"a"=>2, "b"=>1, "c"=>3}
2.7.3 :003 > [4,1,2,1,2].tally
=> {4=>1, 1=>2, 2=>2}
#补充Hash.index()
2.7.3 :002 > {"a"=>2, "b"=>1, "c"=>3}.index(1)
=> "b"
2.7.3 :006 > {"a"=>2, "b"=>1, "c"=>3}.index(2)
=> "a"
2.7.3 :007 > {"a"=>2, "b"=>1, "c"=>3}.index(3)
=> "c"
#补充invert
2.7.3 :020 > {"a"=>2, "b"=>1, "c"=>3}.invert
=> {2=>"a", 1=>"b", 3=>"c"}
2.7.3 :023 > {"a"=>2, "b"=>1, "c"=>3}.invert[1]
=> "b"
2.7.3 :024 > {"a"=>2, "b"=>1, "c"=>3}.invert[2]
=> "a"
2.7.3 :025 > {"a"=>2, "b"=>1, "c"=>3}.invert[3]
=> "c"
整理
def single_number(nums)
nums.tally.key(1)
end
2.7.3 :027 > 1 + 1
=> 2
2.7.3 :028 > 2 - 1
=> 1
def single_number(nums)
nums.uniq.sum * 2 - nums.sum
end
2 + 1 + 2 + 1
-
2 + 2 + 1
=
1
查表法比较慢,但是万用。
<<: [C#] 使用记忆体快取 MemoryCache 增加回应速度
66. Plus One 今天这一题相对单纯、简单一些,但当中也有一些小技巧和观念,还是蛮值得一看的...
话说从前 自从电脑问世以来,若要将程序无缝的转移到其他机器上成功运行,那麽环境架设就是一个必须要优先...
想当一个 Good PHPer,不但要写程序、写注解还要写 API 文件,想到要维护三个地方工程师就...
大家好今天要继续介绍arduino函式库安装与使用 arduino IDE本身会有内建一些函式库让你...
今天我们接续昨日的话题,继续来聊聊AI发展史上的第二次寒冬。 前面提到,AI在1956年达特茅斯会议...