LintCode刷题(入门篇)

来源:互联网 发布:淘宝店在哪找货源 编辑:程序博客网 时间:2024/06/06 07:49

最近在玩LintCode上面的算法题。下面分享一下部分题目的答案。如果其他同学有更好的答案,可以和我交流讨论,本人菜鸟一个,各位大佬多指点。

同时说一下,这个上面的二叉树 和 链表 我不懂,所以这类题目没有做。现在才刚开始玩,做了大概二十来题,以后会持续更新。。。

我是依次一题题往下看的,从入门开始,这边记录也从这里开始吧。部分题目没看懂的,就过了。

二叉树的最大节点(这题参考别人的,二叉树不是很懂)

public TreeNode maxNode(TreeNode root) {  
        // Write your code here  
        ArrayList<TreeNode> result = new ArrayList<TreeNode>();  
        result.add(root);  
        search(root , result);  
        return result.get(0);  
    }  
      
    public void search(TreeNode root , ArrayList<TreeNode> result){  
        if(root == null){  
            return ;  
        }  
        if(result.get(0).val < root.val){  
            result.set(0 , root);  
        }  
        if(root.left != null){  
            search(root.left , result);  
        }  
        if(root.right != null){  
            search(root.right , result);  
        }  
    }  

斐波纳契数列 (这题相对比较简单,没啥好说的)

public int fibonacci(int n) {
        // write your code here
        int a = 0;
        int b = 1;
        int c = 0;
        if (n == 1) {
            return 0;
        } else if (n == 2) {
            return 1;
        } else {
            for(int j = 3; j <= n; j++) {
                c = a + b;
                a = b;
                b = c;
            }
            return c;
        }
    }

矩阵面积(这题更没啥好说的)

public class Rectangle {
    // write your code here
    private int mWidth;
    private int mHeight;


    public Rectangle(int mWidth, int mHeight) {
        this.mWidth = mWidth;
        this.mHeight = mHeight;
    }
    public int getArea() {
        return mWidth * mHeight;
    }
}

整数排序(直接调用API就好了,对于这种千万不要浪费时间)

Arrays.sort(A);


原创粉丝点击