Algorithm ladder III

Dec 27, 28

Binary Search

  • lintcode 61 search-for-a-range

  • lintcode 38 Search a 2D Matrix II, leetcode 240

  • lintcode 160.Find Minimum in Rotated Sorted Array II

  • lintcode 63.Search in Rotated Sorted Array II

  • leetcode 69. Sqrt(x), square root of an integer

  • lintcode 586 Sqrt(x) II, square root of a double

  • lintcode 160.Find Minimum in Rotated Sorted Array II --- TO DO

  • lintcode 63.Search in Rotated Sorted Array II ---- TO DO

  • lintcode 617.Maximum Average Subarray --- TO DO

  • lintcode 437.Copy Books --- TO DO

  • lintcode 183.Wood Cut -- TO DO 這兩題都很有趣黎比。二分法求最優(yōu)

  • Binary tree, Divide and Conquer

  • lintcode 597.Subtree with Maximum Average

  • lintcode 110 Balanced Binary Tree (easy but typical)

lintcode 61 search-for-a-range

簡(jiǎn)單的求first 求last

package algorithm_ladder_III;

/**
 * lintcode 61
 *
 */
public class SearchForARange {
    public int[] searchRange(int[] A, int target) {
        // corner case:
        if (A==null || A.length == 0) {
            return new int[] {-1, -1};
        }
        
        int first = findBoundary(A, target, true);
        if (first == -1) return new int[] {-1, -1};
        int last = findBoundary(A, target, false);
        return new int[] {first, last};
    }
    
    // findFirst = true: find first of target
    // else find last of target;
    private int findBoundary(int[] A, int target, boolean findFirst) {
        int lo = 0, hi = A.length -1;
        while (lo + 1 < hi) {
            int mid = lo + (hi-lo) / 2;
            if ( target > A[mid]) {
                lo = mid;
            } else if (target < A[mid]) {
                hi = mid;
            } else {
                if (findFirst) {
                    hi = mid;
                } else {
                    lo = mid;
                }
            }
        }
        
        if (findFirst) {
            if (A[lo] == target) return lo;
            else if (A[hi] == target) return hi;
            else return -1;
        } else {
            if (A[hi] == target) return hi;
            else if (A[lo] == target) return lo;
            else return -1;
        }
    }
    
    public static void main(String[] args) {
        int[] A = new int[] {5, 7, 7, 8, 8, 10};
        int target = 8;
        SearchForARange s = new SearchForARange();
        int[] res = s.searchRange(A, target);
        System.out.println(res[0] + " " + res[1]); // should be [3, 4]
    }
}

lintcode 38 Search a 2D Matrix II

search a 2D matrix II

要點(diǎn):最優(yōu)解O(m+n) 走anti-diagonal entries.
一般解得化,可以逐行搜索继控;

package algorithm_ladder_III;

/**
 * leetcode 240
 */
public class SearchA2DMatrixII {
    public int searchMatrix(int[][] A, int target) {
        // corner case 
        if (A == null || A.length == 0) 
            return 0;
        
        int i = A.length-1, j = 0; // i^th row, j^th col --- the bottom left corner of the matrix
        int result = 0;
        while (i >= 0 && j < A[0].length) {
            if (A[i][j] > target) {
                i--;
            } else if (A[i][j] < target) {
                j++;
            } else {
                result++;
                i--;
                j++;
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[][] A = new int[3][4];
        A[0] = new int[] {1, 3, 5, 7};
        A[1] = new int[] {2, 4, 7, 8};
        A[2] = new int[] {3, 5, 9, 10};
        int target = 3;
        SearchA2DMatrixII s = new SearchA2DMatrixII();
        System.out.println(s.searchMatrix(A, target)); // should be 2   
    }
}

leetcode 69. Sqrt(x)

package algorithm_ladder_III;

public class Sqrt {
    public int mySqrt(int x) {
        // corner case;
        if (x == 0) return 0;
        
        
        int lo = 1, hi = x;
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            if (mid * mid < x) lo = mid;
            else if (mid * mid > x) hi = mid;
            else return mid;
        }
        System.out.println(lo + " " + hi);
        
        if (hi * hi <= x) return hi;
        else return lo;
    }
    
    public static void main(String[] args) {
        int x = 8;
        Sqrt s = new Sqrt();
        System.out.println(s.mySqrt(x)); // should be 2
    }
}

lintcode 586 Sqrt(x) II

package algorithm_ladder_III;

public class SqrtII {   
    public double sqrt(double x) {
        double lo = 0.0, hi;
        if (x > 1) hi = x;
        else hi = 1;
        
        while (lo + 1e-12 < hi) {
                double mid = lo + (hi-lo) / 2;
                if (x < mid * mid) hi = mid;
                else if (x > mid * mid) lo = mid;
                else return mid;
        }
        return lo;
    }

    public static void main(String[] args) {
        double x = 2;
        SqrtII s = new SqrtII();
        System.out.println(s.sqrt(x)); // should be 1.41421356
    }
}

lintcode 597.Subtree with Maximum Average

qoute

/*和path祭钉,Minimum Subtree這類題差不多队丝,
* 這一類的題目都可以這樣做:
* 開(kāi)一個(gè)ResultType的變量result,
* 來(lái)儲(chǔ)存擁有最大average的那個(gè)node的信息。
* 然后用分治法來(lái)遍歷整棵樹(shù)傅事。
* 一個(gè)小弟找左子數(shù)的average茎辐,一個(gè)小弟找右子樹(shù)的average宪郊。
* 然后通過(guò)這兩個(gè)來(lái)計(jì)算當(dāng)前樹(shù)的average。
* 同時(shí)拖陆,我們根據(jù)算出來(lái)的當(dāng)前樹(shù)的average決定要不要更新result弛槐。
* 當(dāng)遍歷完整棵樹(shù)的時(shí)候,
* result里記錄的就是擁有最大average的子樹(shù)的信息依啰。
/

package algorithm_ladder_III.subtree_with_maximum_average;


public class SubtreeWithMaxAverage {
    class ResultType {
        int count;
        int sum;
        public ResultType(int count, int sum) {
            this.count = count;
            this.sum = sum;
        }
    }
    
    private TreeNode ResultNode = null;
    private double MaxAvg = Double.MIN_VALUE;
    public TreeNode findSubtree(TreeNode root) {
        sumAndCount(root);
        return ResultNode;
    }
    
    private ResultType sumAndCount(TreeNode root) {
        if (root == null) {
            return new ResultType(0, 0);
        }
        
        ResultType left = sumAndCount(root.left);
        ResultType right = sumAndCount(root.right);
        int newSum = left.sum + right.sum + root.val;
        int newCount = left.count + right.count + 1;
        ResultType r = new ResultType(newCount, newSum);
        if (MaxAvg < ((double) newSum / (double) newCount)) {
            MaxAvg = ((double) newSum / (double) newCount);
            ResultNode = root;
        }
        return r;
    }
    
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(1); left.left = new TreeNode(10); left.right = new TreeNode(15);
        TreeNode right = new TreeNode(2); right.left = new TreeNode(4); right.right = new TreeNode(5);
        root.left = left; root.right = right;
        
        SubtreeWithMaxAverage s = new SubtreeWithMaxAverage();
        
        TreeNode node = s.findSubtree(root);
        System.out.println(node.val); // should be 1;
    }
}

lintcode 110 Balanced Binary Tree (easy but typical)

問(wèn)題是true or false乎串,按照divide and conquer,helper function也可以是true and false速警,另外需要傳遞的是depth這個(gè)量叹誉,所以naturally想到一個(gè)result type包含這兩個(gè)量鸯两。

比較smart的解法是把這兩個(gè)量合成一個(gè)量,false用-1表示长豁。(解法2)

package algorithm_ladder_III.normal_binary_tree;

/**
 * leetcode 110
 * 通過(guò)求深度來(lái)求判斷是否是balanced
 */
public class BalancedBinaryTree {
    class ResultType {
        int depth;
        boolean isBalanced;
        ResultType(int depth, boolean isBalanced) {
            this.depth = depth;
            this.isBalanced = isBalanced;
        }
    }
    
    public boolean isBalanced(TreeNode root) {
        ResultType res = checkHeightAndBalance(root);
        return res.isBalanced;
    }
    
    private ResultType checkHeightAndBalance(TreeNode root) {
        if (root == null) return new ResultType(0, true);
        
        ResultType left = checkHeightAndBalance(root.left);
        ResultType right = checkHeightAndBalance(root.right);
        int newDepth = 1+ Math.max(left.depth, right.depth);
        boolean newIsBalanced = left.isBalanced && right.isBalanced && Math.abs(left.depth - right.depth) <= 1;
        return new ResultType(newDepth, newIsBalanced);
    }
}

or

package algorithm_ladder_III.normal_binary_tree;

/**
 * Alternative solution to leetcode 110
 */
public class BalancedBinaryTreeII {
    public boolean isBalanced(TreeNode root) {
        int r = getHeight(root);
        return r != -1;
    }
    
    public int getHeight(TreeNode root) {
        if (root == null) return 0;
        
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        
        if (left == -1 || right == -1) return -1;
        if (Math.abs(left - right) <= 1) return 1 + Math.max(left, right);
        return -1;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钧唐,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蕉斜,更是在濱河造成了極大的恐慌逾柿,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宅此,死亡現(xiàn)場(chǎng)離奇詭異机错,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)父腕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門弱匪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人璧亮,你說(shuō)我怎么就攤上這事萧诫。” “怎么了枝嘶?”我有些...
    開(kāi)封第一講書人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵帘饶,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我群扶,道長(zhǎng)及刻,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任竞阐,我火速辦了婚禮缴饭,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘骆莹。我一直安慰自己颗搂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布幕垦。 她就那樣靜靜地躺著丢氢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪先改。 梳的紋絲不亂的頭發(fā)上卖丸,一...
    開(kāi)封第一講書人閱讀 51,245評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音盏道,去河邊找鬼。 笑死载碌,一個(gè)胖子當(dāng)著我的面吹牛猜嘱,可吹牛的內(nèi)容都是我干的衅枫。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼朗伶,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼弦撩!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起论皆,我...
    開(kāi)封第一講書人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤益楼,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后点晴,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體感凤,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年粒督,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了陪竿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡屠橄,死狀恐怖族跛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情锐墙,我是刑警寧澤礁哄,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站溪北,受9級(jí)特大地震影響桐绒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜刻盐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一掏膏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧敦锌,春花似錦馒疹、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至听想,卻和暖如春腥刹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背汉买。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工衔峰, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓垫卤,卻偏偏與公主長(zhǎng)得像威彰,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子穴肘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

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