LintCode 線段樹系列問題(線段樹的構(gòu)造纵揍,線段樹的構(gòu)造||顿乒,線段樹的查詢,線段樹的查詢II,線段樹的修改)

線段樹(又稱區(qū)間樹), 是一種高級數(shù)據(jù)結(jié)構(gòu)泽谨,他可以支持這樣的一些操作:

  • 查找給定的點包含在了哪些區(qū)間內(nèi)
  • 查找給定的區(qū)間包含了哪些點

線段樹的構(gòu)造

題目

線段樹是一棵二叉樹璧榄,他的每個節(jié)點包含了兩個額外的屬性start和end用于表示該節(jié)點所代表的區(qū)間。start和end都是整數(shù)吧雹,并按照如下的方式賦值:

  • 根節(jié)點的 start 和 end 由 build 方法所給出骨杂。
  • 對于節(jié)點 A 的左兒子,有 start=A.left, end=(A.left + A.right) / 2雄卷。
  • 對于節(jié)點 A 的右兒子搓蚪,有 start=(A.left + A.right) / 2 + 1, end=A.right。
  • 如果 start 等于 end, 那么該節(jié)點是葉子節(jié)點丁鹉,不再有左右兒子妒潭。

實現(xiàn)一個 build 方法,接受 start 和 end 作為參數(shù), 然后構(gòu)造一個代表區(qū)間 [start, end] 的線段樹揣钦,返回這棵線段樹的根雳灾。

代碼

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end) {
 *         this.start = start, this.end = end;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param start, end: Denote an segment / interval
     *@return: The root of Segment Tree
     */
    public SegmentTreeNode build(int start, int end) {
        // write your code here
        if(start > end) {  // check core case
            return null;
        }
       
        SegmentTreeNode root = new SegmentTreeNode(start, end);
       
        if(start < end) {
            int mid = (start + end) / 2;
            root.left = build(start, mid);
            root.right = build(mid+1, end);
        }
        return root;
    }
}

線段樹的構(gòu)造 II

題目

跟上題類似,增加一個屬性max冯凹,記錄區(qū)間最大值

代碼

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end, max;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end, int max) {
 *         this.start = start;
 *         this.end = end;
 *         this.max = max
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param A: a list of integer
     *@return: The root of Segment Tree
     */
    public SegmentTreeNode build(int[] A) {
        // write your code here
        return buildTree(0, A.length - 1, A);
    }

    public SegmentTreeNode buildTree(int start, int end, int[] A) {
        if (start > end)
            return null;

        if (start == end) {
            return new SegmentTreeNode(start, end, A[start]);
        }
        
        SegmentTreeNode node = new SegmentTreeNode(start, end, A[start]);
        int mid = (start + end) / 2;
        node.left = this.buildTree(start, mid, A);
        node.right = this.buildTree(mid + 1, end, A);
        node.max = Math.max(node.left.max, node.right.max);
        
        return node;
    }
}

線段樹的查詢

題目

對于一個有n個數(shù)的整數(shù)數(shù)組谎亩,在對應(yīng)的線段樹中, 根節(jié)點所代表的區(qū)間為0-n-1, 每個節(jié)點有一個額外的屬性max,值為該節(jié)點所代表的數(shù)組區(qū)間start到end內(nèi)的最大值谈竿。

為SegmentTree設(shè)計一個 query 的方法团驱,接受3個參數(shù)root, start和end,線段樹root所代表的數(shù)組中子區(qū)間[start, end]內(nèi)的最大值空凸。

樣例
對于數(shù)組 [1, 4, 2, 3], 對應(yīng)的線段樹為:
query(root, 1, 1), return 4

query(root, 1, 2), return 4

query(root, 2, 3), return 3

query(root, 0, 2), return 4


Paste_Image.png

代碼

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end, max;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end, int max) {
 *         this.start = start;
 *         this.end = end;
 *         this.max = max
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param root, start, end: The root of segment tree and 
     *                         an segment / interval
     *@return: The maximum number in the interval [start, end]
     */
    public int query(SegmentTreeNode root, int start, int end) {
        // write your code here
        if(root == null)
        {
            return Integer.MIN_VALUE;
        }
        
        if(start == root.start && root.end == end) { // 相等 
            return root.max;
        }
        
        
        
        int mid = (root.start + root.end)/2;
        int leftmax = Integer.MIN_VALUE, rightmax = Integer.MIN_VALUE;
        // 左子區(qū)
        if(start <= mid) {
            if( mid < end) { // 分裂 
                leftmax =  query(root.left, start, mid);
            } else { // 包含 
                leftmax = query(root.left, start, end);
            }
            // leftmax = query(root.left, start, Math.min(mid,end));
        }
        // 右子區(qū)
        if(mid < end) { // 分裂 3
            if(start <= mid) {
                rightmax = query(root.right, mid+1, end);
            } else { //  包含 
                rightmax = query(root.right, start, end);
            }
            //rightmax = query(root.right, Math.max(mid+1,start), end);
        }  
        // else 就是不相交
        return Math.max(leftmax, rightmax);
    }
}

線段樹查詢 II

題目

對于一個數(shù)組,我們可以對其建立一棵 線段樹, 每個結(jié)點存儲一個額外的值 count 來代表這個結(jié)點所指代的數(shù)組區(qū)間內(nèi)的元素個數(shù). (數(shù)組中并不一定每個位置上都有元素)

實現(xiàn)一個 query 的方法寸痢,該方法接受三個參數(shù) root, start 和 end, 分別代表線段樹的根節(jié)點和需要查詢的區(qū)間呀洲,找到數(shù)組中在區(qū)間[start, end]內(nèi)的元素個數(shù)。

樣例
對于數(shù)組 [0, 空啼止,2, 3], 對應(yīng)的線段樹為:

Paste_Image.png

query(1, 1), return 0

query(1, 2), return 1

query(2, 3), return 2

query(0, 2), return 2

代碼

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end, count;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end, int count) {
 *         this.start = start;
 *         this.end = end;
 *         this.count = count;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param root, start, end: The root of segment tree and 
     *                         an segment / interval
     *@return: The count number in the interval [start, end]
     */
    public int query(SegmentTreeNode root, int start, int end) {
        // write your code here
        if(start > end || root==null)
            return 0;
        if(start <= root.start && root.end <= end) { // 相等 
            return root.count;
        }
        
        int mid = (root.start + root.end)/2;
        int leftsum = 0, rightsum = 0;
        // 左子區(qū)
        if(start <= mid) {
            if( mid < end) { // 分裂 
                leftsum =  query(root.left, start, mid);
            } else { // 包含 
                leftsum = query(root.left, start, end);
            }
        }
        // 右子區(qū)
        if(mid < end) { // 分裂 3
            if(start <= mid) {
                rightsum = query(root.right, mid+1, end);
            } else { //  包含 
                rightsum = query(root.right, start, end);
            } 
        }  
        // else 就是不相交
        return leftsum + rightsum;
    }
}

線段樹的修改

題目

對于一棵 最大線段樹, 每個節(jié)點包含一個額外的 max 屬性道逗,用于存儲該節(jié)點所代表區(qū)間的最大值。

設(shè)計一個 modify 的方法献烦,接受三個參數(shù) root滓窍、 index 和 value。該方法將 root 為跟的線段樹中 [start, end] = [index, index] 的節(jié)點修改為了新的 value 巩那,并確保在修改后吏夯,線段樹的每個節(jié)點的 max 屬性仍然具有正確的值此蜈。

樣例
對于線段樹:

Paste_Image.png

代碼

/**
 * Definition of SegmentTreeNode:
 * public class SegmentTreeNode {
 *     public int start, end, max;
 *     public SegmentTreeNode left, right;
 *     public SegmentTreeNode(int start, int end, int max) {
 *         this.start = start;
 *         this.end = end;
 *         this.max = max
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param root, index, value: The root of segment tree and 
     *@ change the node's value with [index, index] to the new given value
     *@return: void
     */
    public void modify(SegmentTreeNode root, int index, int value) {
        // write your code here
        if(root.start >= index && root.end <= index) { // 查找到
            root.max = value;
            return;
        }
        
        // 查詢
        int mid = (root.start + root.end) / 2;
        if(root.start <= index && index <=mid) {
            modify(root.left, index, value);
        }
        
        if(mid < index && index <= root.end) {
            modify(root.right, index, value);
        }
        //更新
        root.max = Math.max(root.left.max, root.right.max);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市噪生,隨后出現(xiàn)的幾起案子裆赵,更是在濱河造成了極大的恐慌,老刑警劉巖跺嗽,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件战授,死亡現(xiàn)場離奇詭異,居然都是意外死亡桨嫁,警方通過查閱死者的電腦和手機(jī)植兰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來璃吧,“玉大人钉跷,你說我怎么就攤上這事《且荩” “怎么了爷辙?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長朦促。 經(jīng)常有香客問我膝晾,道長,這世上最難降的妖魔是什么务冕? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任血当,我火速辦了婚禮,結(jié)果婚禮上禀忆,老公的妹妹穿的比我還像新娘臊旭。我一直安慰自己,他們只是感情好箩退,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布离熏。 她就那樣靜靜地躺著,像睡著了一般戴涝。 火紅的嫁衣襯著肌膚如雪滋戳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天啥刻,我揣著相機(jī)與錄音奸鸯,去河邊找鬼。 笑死可帽,一個胖子當(dāng)著我的面吹牛娄涩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播映跟,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蓄拣,長吁一口氣:“原來是場噩夢啊……” “哼扬虚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起弯蚜,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤孔轴,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后碎捺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體路鹰,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年收厨,在試婚紗的時候發(fā)現(xiàn)自己被綠了晋柱。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡诵叁,死狀恐怖雁竞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拧额,我是刑警寧澤碑诉,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站侥锦,受9級特大地震影響进栽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜恭垦,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一快毛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧番挺,春花似錦唠帝、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至禁荸,卻和暖如春右蒲,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背赶熟。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留陷嘴,地道東北人映砖。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像灾挨,于是被迫代替她去往敵國和親邑退。 傳聞我的和親對象是個殘疾皇子竹宋,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

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