偶尔分享一下新歌...
题目连结:https://leetcode.com/problems/majority-element/
题目重点:The majority element is the element that appears more than ⌊n / 2⌋ times.
这句可以导出另一种解法。
整理:
# @param {Integer[]} nums
# @return {Integer}
def majority_element(nums)
end
p majority_element([3,2,3]) #=>3
p majority_element([[2,2,1,1,1,2,2]]) #=>2
依照前一题的分享,已经知道tally用法
2.7.3 :083 > [2,2,1,1,1,2,2].tally
=> {2=>4, 1=>3}
#那就找出value中最大值的Key就可以了。(4与3,最大的那个的key)
英文不好,中文也不好...
查到hash也可以用max_by。
https://stackoverflow.com/questions/6040494/how-to-find-the-key-of-the-largest-value-hash
#Array 手册上的示范。
2.7.3 :009 > ["abcdefg", "ascv", "zzz"].max_by {|string|string.length}
=> "abcdefg"
2.7.3 :010 > ["abcdefg", "ascv", "zzz"].max_by(2) {|string|string.length}
=> ["abcdefg", "ascv"]
#Hash
2.7.3 :011 > {4=>4, 1=>3, 3=>5}.max_by{|key, value|key}
=> [4, 4]
2.7.3 :012 > {4=>4, 1=>3, 3=>5}.max_by{|key, value|value}
=> [3, 5]
#ans
2.7.3 :013 > [2,2,1,1,1,2,2].tally
=> {2=>4, 1=>3}
2.7.3 :014 > [2,2,1,1,1,2,2].tally.max_by{|key, value|value}
=> [2, 4]
2.7.3 :015 > [2,2,1,1,1,2,2].tally.max_by{|key, value|value}.first
=> 2
整理後
def majority_element(nums)
nums.tally.max_by{|key, value| value}.first
end
如果真的无法理解,常态分布时,众数会与中位数重合,那就先观察吧。
2.7.3 :061 > [3,2,3].sort.map.with_index {|num, index|[index, num]}.to_h
=> {0=>2, 1=>3, 2=>3}
2.7.3 :062 > [1, 1, 1, 2, 2, 2, 2].sort.map.with_index {|num, index|[index, num]}.to_h
=> {0=>1, 1=>1, 2=>1, 3=>2, 4=>2, 5=>2, 6=>2}
解法
def majority_element(nums)
nums.sort[nums.size/2]
end
补充提醒:
#都Integer时," / "号,不带小数点
2.7.3 :063 > 7/2
=> 3
#除非Float
2.7.3 :067 > 7/2.0
=> 3.5
2.7.3 :068 > 7.0/2
=> 3.5
#然後如果[]里带Float,只看整数部分。
2.7.3 :069 > [1, 2, 3][1.4]
=> 2
2.7.3 :070 > [1, 2, 3][1.8]
=> 2
打了高端,解题也不会变厉害的,还是要乖乖练习T_T...
>>: [ASP.Net MVC] 取得 Request 常用资讯 (IP, 作业系统, 浏览器, 呼叫网址)
还记得之前我装了个相机吗? 当初很害怕地把它组装上去,就怕插错或是折到排线,以至於他不能正常动作 那...
我只是一个小新手 因为有使用者需求,当时也找很久想说纪录一下 下拉清单,要多一条线 像这样 当初在国...
接下来讲讲如何发布程序 1.首先在专案上按右键点发布 2.目标选择资料夹 3.选择资料夹位置 (一般...
开始实做发给 telegram 的回覆 telegram 使用 axios 来要求 telegram...
开发 mvp ...