算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 给定数字的频率查询中位数,我们先来看题面:
https://leetcode-cn.com/problems/find-median-given-frequency-of-numbers/
解题
法一:利用正序和倒叙
select
avg(Number) as median
from
(select
Number,
SUM(Frequency) OVER(ORDER BY Number) AS DN,
SUM(Frequency) OVER(ORDER BY Number desc) AS UP,
SUM(Frequency) OVER() AS TOTAL
from
Numbers) A
where
DN >= TOTAL/2 AND UP >= TOTAL/2
法二:利用变量
select
avg(Number) median
from
(select
Number,
@num as bef,
@num := @num+Frequency as aft
from
(select @num:=0 )B ,Numbers
order by Number) A
where
bef <= @num/2 and aft >= @num/2
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: