kth smallest element in an array

Question from lintcode

Given an unsorted array, find the kth smallest element.

Idea

Use any sort algorithm you are familiar with. I implemented a heap with an array. This array implementation is brought from Mark Allen Weiss 's Data Structures and Algorithm Analysis in C in my university class.

public class Solution {
    /*
     * @param k: An integer
     * @param nums: An integer array
     * @return: kth smallest element
     */
    public int kthSmallest(int k, int[] nums) {

        assert nums.length > 0;

        Heap heap = new Heap(nums.length);
        for(int n: nums) {
            heap.add(n);
        }

        assert heap.size() > 0 && k <= heap.size();

        int out = Integer.MIN_VALUE;
        for(int i = 0; i < k; i++) {
            out = heap.pop();
        }
        return out;
    }
    
    class Heap {
        private int[] hp;
        private int lastPos = 0;

        private int childPosLeft(int n) {
            return n * 2;
        }

        private int childPosRight(int n) {
            return childPosLeft(n) + 1;
        }

        private int parentPos(int n ) {
            return n/2;
        }

        private int root() {
            return 1;
        }

        private boolean hasChild(int pos) {
            return childPosLeft(pos) <= lastPos;
        }

        private  int smallerChildPos(int pos) {
            if (childPosLeft(pos) == lastPos) 
                return childPosLeft(pos); 
            if (hp[childPosLeft(pos)] > hp[childPosRight(pos)])
                return childPosRight(pos);
            return childPosLeft(pos);
        }

        public int size() {
            return lastPos;
        }

        public Heap(int size) {
            hp = new int[size + 1];
            hp[0] = Integer.MIN_VALUE;
        }

        public void add(int num) {
            lastPos++;
            // heap的精髓:只要你比我爸爸有錢(排序高, 這裏是越小越高)田轧,我叫我爸下來給你當(dāng)兒子
            int i;
            for(i = lastPos; hp[parentPos(i)] > num; i = parentPos(i))
                hp[i] = hp[parentPos(i)];
            hp[i] = num;
        }

        public int pop() {
            int output = hp[root()];
            int i = root();
            int lastElement = hp[lastPos--];
            // 孫子上去頂層,往下走,見到爸爸們就讓他們向上爬枢赔,爬上去了空出來的位子你坐
            hp[i] = lastElement;
            while(hasChild(i)) {
                int child = smallerChildPos(i);
                if (hp[i] > hp[child]) {
                    hp[i] = hp[child];
                    hp[child] = lastElement;
                    i = child;
                } else {
                    break;
                }
            }
            return output;
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末课舍,一起剝皮案震驚了整個濱河市柜砾,隨后出現(xiàn)的幾起案子驾中,更是在濱河造成了極大的恐慌疼电,老刑警劉巖玲躯,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件据德,死亡現(xiàn)場離奇詭異,居然都是意外死亡府蔗,警方通過查閱死者的電腦和手機(jī)晋控,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來姓赤,“玉大人赡译,你說我怎么就攤上這事〔幻” “怎么了蝌焚?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長誓斥。 經(jīng)常有香客問我只洒,道長,這世上最難降的妖魔是什么劳坑? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任毕谴,我火速辦了婚禮,結(jié)果婚禮上距芬,老公的妹妹穿的比我還像新娘涝开。我一直安慰自己,他們只是感情好框仔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布舀武。 她就那樣靜靜地躺著,像睡著了一般离斩。 火紅的嫁衣襯著肌膚如雪银舱。 梳的紋絲不亂的頭發(fā)上瘪匿,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天,我揣著相機(jī)與錄音寻馏,去河邊找鬼棋弥。 笑死,一個胖子當(dāng)著我的面吹牛操软,可吹牛的內(nèi)容都是我干的嘁锯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼聂薪,長吁一口氣:“原來是場噩夢啊……” “哼家乘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起藏澳,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤仁锯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后翔悠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體业崖,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年蓄愁,在試婚紗的時候發(fā)現(xiàn)自己被綠了双炕。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡撮抓,死狀恐怖妇斤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情丹拯,我是刑警寧澤站超,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站乖酬,受9級特大地震影響死相,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜咬像,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一算撮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧县昂,春花似錦肮柜、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蔑赘。三九已至狸驳,卻和暖如春预明,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背耙箍。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工撰糠, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人辩昆。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓阅酪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親汁针。 傳聞我的和親對象是個殘疾皇子术辐,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評論 2 355

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