Kth Quantiles. Θ(nlgk)

The kth quantiles of an n-element set are the k-1 order statistics that divide the sorted set into k equal-sized sets (to within 1). Give an O(nlgk)-time algorithm to list the kth quantiles of a set.

I did a lot of jobs to figure out what the hell the question is actually talking about. In fact, there would have been k groups fragments in an n-size set/list which are divided by k-1 order statistics named quantiles after evaluating one's algorithm. At first, the set/list is unsorted and it can be hardly unsorted after execution.

So hereafter I make up 2 functions - k_quantiles_sorted_n(which costs Θ(n)) & k_quantiles_sorted_lgk(which takes Θ(lgk)) - to solve the already-sorted-array problems. In these cases, I just work out an array of indices which are on behave of the positions of dividers.

In the end, I take out the original problem with function k_quantiles_unsorted_nlgk and make it by recursion which consumes Θ(nlgk). As you'll see below, the gross problem is separated into 2 subroutines, each of n(1-1/k)/2 to n/2 scale.

This works homogeneous with the same size of group when the number of elements (aka n) is ak+k?1 for a positive integer a. Once it were a different number, the interval among groups would be heterogeneous. some additive care with rounding needs to be taken in order to avoid creating two segments that differ by more than 1.

The inherent consumption takes place in the select function which takes up to Θ(n) time. The base case is that the subproblem is divided into a scale of T(n/k) with a item of Θ(1) so that you could immediately return. The recursion here is

T(n) <= 2T(n/2) + Θ(n) <= 4T(n/4) + 2Θ(n) <= 8T(n/8) + 3Θ(n) ...
<= kT(n/k) + lgkΘ(n) = Θ(nlgk)

It would be nice to illustrate by a binary recursion tree with a depth of lgk and leaves of T(n/k). As we could see, the last subproblem scale determines the log part in final Θ(nlgk), which reflected by the depth of the recursion tree. Furthermore, we could find that if the last problem scale is Θ(1), that is n/n, then the consumption goes up to Θ(nlgn), which means the groups count will be the last divisor. The less groups we divide at last, the less log part we spend.

i.e. Note that the slice of array in python is returning a new array(aka slice for copy) which doesn't correspond to Swift. I've spent a lot of time getting rid of the startIndex & endIndex parameters using slice of array. But it all went in vain as a result since we cannot regard the slice as a reference of original array partially. Probably it'd take effect with memoryview or something which is quite annoying.

As we used to say, unit tests run first.
Test Driven Code:

import unittest

class TestCase(unittest.TestCase):

    def setUp(self):
        self.maxDiff = None

    def test_k_quantiles_sorted(self):
        for j in range(0, 100):
            n = randint(10, 20)
            k = randint(0, n+1)
            # l = k_quantiles_sorted_n(n, k, 0)
            l = k_quantiles_sorted_lgk(n, k)
            count = len(l)
            self.assertGreaterEqual(count, 0)
            if count == 0:
                continue
            sentinel_1 = l[0]
            sentinel_2 = -1
            self.assertLess(sentinel_1, n) 
            for i in range(1, count+1):
                scope = 0
                if i == count:
                    scope = n - l[i-1] - 1
                else:
                    self.assertLess(l[i], n) 
                    scope = l[i] - l[i-1] - 1
                difference = abs(sentinel_1 - scope)
                self.assertLessEqual(difference, 1)
                if difference == 0:
                    continue
                else:
                    if sentinel_2 < 0:
                        sentinel_2 = difference
                    else:
                        self.assertEqual(sentinel_2, difference)

    def test_k_quantiles_unsorted_nlgk(self):
        for j in range(0, 100):
            n = randint(50, 100)
            k = randint(0, n+1)
            l = list(range(0, n))
            quantiles = k_quantiles_unsorted_nlgk(l, 0, len(l)-1, k)
            count = len(quantiles)
            self.assertGreaterEqual(count, 0)
            if count == 0:
                continue
            dividor = k - 1
            remain = n - dividor 
            base = remain // k
            additive = base + 1
            additiveGroup = remain % k
            baseGroup = k - additiveGroup
            current = -1
            quantiles.append(n)
            for i in range(0, len(quantiles)):
                scope = quantiles[i]-current-1
                current = quantiles[i]
                self.assertTrue(scope==base or scope==additive)

                if scope == base:
                    baseGroup -= 1
                elif scope == additive:
                    additiveGroup -= 1
            self.assertTrue(baseGroup==0 and additiveGroup==0)


if __name__ == '__main__':
    unittest.main()

Then it goes with source code:

def k_quantiles_sorted_n(n:int, k:int, base:int) -> []:
    if k <= 1 or k > n+1:
        return[]
    remainder = k % 2
    if remainder:
        midst = n // k
        remains = n-midst-2
        n_left = remains // 2
        n_right = remains - n_left
        k_child = (k-1) // 2
        left = base + n_left
        right = base + n - n_right - 1
        return k_quantiles_sorted_n(n_left, k_child, base) + \
        [left, right] + k_quantiles_sorted_n(n_right, k_child, right+1)
    else:
        k_child = k // 2
        n_left = n // 2
        n_right = n - n_left - 1
        halver = base + n_left
        return k_quantiles_sorted_n(n_left, k_child, base) + \
        [halver] + k_quantiles_sorted_n(n_right, k_child, halver+1)

def k_quantiles_sorted_lgk(n:int, k:int) -> []:
    if k < 2 or k > n+1:
        return[]
    dividor = k - 1
    remain = n - dividor 
    base = remain // k
    additiveGroup = remain % k
    additiveDividor = additiveGroup - 1
    baseGroup = k - additiveGroup
    baseDividor = baseGroup - 1
    if additiveGroup > 0:
        baseDividor += 1
    quantiles = []
    current = -1
    for i in range(0, baseDividor):
        current += base+1
        quantiles.append(current)
    for j in range(0, additiveDividor):
        current += base+2
        quantiles.append(current)
    return quantiles

def k_quantiles_unsorted_nlgk(array:[], startIndex:int, endIndex:int, k:int) -> []:
    n = endIndex - startIndex + 1
    if k < 2 or k > n+1:
        return[]
    k_child = k // 2
    remainder = k % 2
    if remainder:
        midstCount = n // k
        remainCount = n - midstCount - 2
        leftCount = remainCount // 2
        rightCount = remainCount - leftCount
        leftIndex = startIndex + leftCount
        rightIndex = leftIndex + midstCount + 1
        localLeftIndex = leftCount
        localRightIndex = midstCount
        left = select(array, startIndex, endIndex, localLeftIndex)
        right = select(array, leftIndex+1, endIndex, localRightIndex)
        return k_quantiles_unsorted_nlgk(array, startIndex, leftIndex-1, k_child) + \
        [left, right] + k_quantiles_unsorted_nlgk(array, rightIndex+1, endIndex, k_child)
    else:
        leftCount = n // 2
        halverIndex = startIndex + leftCount
        localHalverIndex = leftCount
        halver = select(array, startIndex, endIndex, localHalverIndex)
        return k_quantiles_unsorted_nlgk(array, startIndex, halverIndex-1, k_child) + \
        [halver] + k_quantiles_unsorted_nlgk(array, halverIndex+1, endIndex, k_child)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末趁矾,一起剝皮案震驚了整個(gè)濱河市种柑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖弃揽,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異遵岩,居然都是意外死亡意敛,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進(jìn)店門立轧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來格粪,“玉大人,你說我怎么就攤上這事氛改≌饰” “怎么了?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵平窘,是天一觀的道長吓肋。 經(jīng)常有香客問我,道長瑰艘,這世上最難降的妖魔是什么是鬼? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任,我火速辦了婚禮紫新,結(jié)果婚禮上均蜜,老公的妹妹穿的比我還像新娘。我一直安慰自己芒率,他們只是感情好囤耳,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著偶芍,像睡著了一般充择。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上匪蟀,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天椎麦,我揣著相機(jī)與錄音,去河邊找鬼材彪。 笑死观挎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的段化。 我是一名探鬼主播嘁捷,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼显熏!你這毒婦竟也來了雄嚣?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤喘蟆,失蹤者是張志新(化名)和其女友劉穎缓升,沒想到半個(gè)月后夷磕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡仔沿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年坐桩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片封锉。...
    茶點(diǎn)故事閱讀 38,566評論 1 339
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡绵跷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出成福,到底是詐尸還是另有隱情碾局,我是刑警寧澤,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布奴艾,位于F島的核電站净当,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蕴潦。R本人自食惡果不足惜像啼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望潭苞。 院中可真熱鬧忽冻,春花似錦、人聲如沸此疹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蝗碎。三九已至湖笨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蹦骑,已是汗流浹背慈省。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留脊串,地道東北人辫呻。 一個(gè)月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓清钥,卻偏偏與公主長得像琼锋,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子祟昭,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,306評論 0 10
  • 看完了《鋼之煉金術(shù)師》缕坎,還是會被里面人物的品質(zhì)、人與人之間的感情篡悟、信任而感動谜叹。 最想記錄的是第二代貪婪說的“我想要...
    櫻苔閱讀 303評論 0 1
  • 工作外的半小時(shí)匾寝,決定你的人生高度,最近通過簡書認(rèn)識了糖果荷腊,她利用工作外8小時(shí)艳悔,堅(jiān)持寫簡書,從她的簡書中了解女仰,她離異...
    studay閱讀 590評論 3 10
  • 兒時(shí)的端午是那樣的溫馨有趣又讓人難忘猜年,而今的端午卻讓人感到蕩然猶存,是歲月的原故還是成長經(jīng)歷所致呢疾忍?總之是中國傳統(tǒng)...
    耕耘者小牛閱讀 220評論 0 2
  • 1,缺啥補(bǔ)啥乔外,怕啥練啥; 2,一切為我所用一罩,所用為團(tuán)隊(duì)家杨幼; 3,我想變聂渊,我要變差购,我不得不變,我會變得越來越好汉嗽。 今...
    房傲東閱讀 86評論 0 0