注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
1. Merge Two Sorted Lists
2. Sparse Matrix Multiplication
3. 挂在这道:
给一个n列类似俄罗期方块的盘, 往下掉方块. 方块定义如下:
class Block {
iatsapp
后面花了好几天用segment tree给解了第3题.
- public class FallingBlock {
- static class Block {
- int left;
- int right;
- int height;
- public Block(int left, int right, int height) {
- this.left = left;
- this.right = right;
- this.height = height;
- }
- }
- private int boardWidth;
- int[] heights;
- // width is the board width
- public FallingBlock(int width) {
- // Height of segment tree
- int x = (int) (Math.ceil(Math.log(width) / Math.log(2)));
- // Maximum size of segment tree
- int maxSize = 2 * (int) Math.pow(2, x) - 1;
- heights = new int[maxSize]; // Memory allocation
- boardWidth = width;
- }
- public void fallBlock(Block block) throws IllegalArgumentException {
- fallBlockInternal(block, 0, boardWidth - 1, 0);
- }
- public int fallBlockInternal(Block block, int start, int end, int index) {
- // haven't init this segment yet
- if (heights[index] == 0) heights[index] = heights[(index - 1) / 2];
- if (start >= block.left && start <= block.right) {
- // If segment of this node is a part of given range, then
- heights[index] += block.height;
- // System.out.println("start:" + start + " end:" + end + " index:" + index + " height:" + heights[index]);
- return heights[index];
- } else if (start > block.right || end < block.left) {
- // If segment of this node is outside the given range
- // System.out.println("start:" + start + " end:" + end + " index:" + index + " height:" + heights[index]);
- return heights[index];
- } else {
- // If a part of this segment overlaps with the given range
- int mid = (start + end) >>> 1;
- heights[index] = Math.max(
- fallBlockInternal(block, start, mid, index * 2 + 1),
- fallBlockInternal(block, mid + 1, end, index * 2 + 2));
- // System.out.println("start:" + start + " end:" + end + " index:" + index + " height:" + heights[index]);
- return heights[index];
- }
- }
- public int getMaxHeight() {
- return heights[0];
- }
- public static void main(String[] args) throws Exception {
- FallingBlock fallingBlock = new FallingBlock(100);
- fallingBlock.fallBlock(new Block(20, 50, 1));
- fallingBlock.fallBlock(new Block(30, 70, 2));
- fallingBlock.fallBlock(new Block(10, 40, 3));
- // fallingBlock.fallBlock(new Block(80, 90, 10));
- System.out.println("max height is " + fallingBlock.getMaxHeight());
- }
- }
复制代码
|