Leetcode Notes - 刷题随笔

200. Numbers of Islands
***********************
class Solution {
    // 首先定义四个方向的向量,方便计算矩阵上下左右的位置
    final static int [][]dirs = {{-1, 0},
                                 {1, 0},
                                 {0, -1},
                                 {0, 1}
                                 };
    public int numIslands(char[][] grid) {
        // corner case
        if (grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        int count = 0;
        final int rows = grid.length;
        final int cols = grid[0].length;
        // 用DFS遍历所有的相邻‘1‘的位置
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++){
                if (grid[i][j] == ‘1‘){
                    count++;
                    dfs(grid, i, j, rows, cols);
                }
            }
        return count;
    }

    public void dfs(char[][]grid, int x, int y, int rows, int cols){
        if (x < 0 || x >= rows || y < 0 || y >= cols || grid[x][y] == ‘0‘){
            return;
        }
        grid[x][y] = ‘0‘;
        for (int []dir : dirs){
            int next_x = dir[0] + x;
            int next_y = dir[1] + y;
            dfs(grid, next_x, next_y, rows, cols);
        }
    }
}
***************************************

700. Search in a Binary Search Tree

701. Insert into a BST
***************************************
    if root:
        if target < root and not root.left:
            into(root.left)
        elif target > root and not root.right:
            into(root.right)
        else:
            if target < root:
                root.left = target
            else:
                root.right = target

#63. Unique Path
    方法1:动态规划问题,从下至上递推求解
    int uniquePaths(int m, int n) {
        if (m==0||n==0)
            return 0;
        auto f = vector<vector<int>>(n+1, vector<int>(m+1, 0));
        f[1][1] = 1;
        for (int y = 1; y <= n; y++){
            for (int x = 1; x <= m; x++){
                if (x==1 && y==1){
                    continue;
                }
                else{
                    f[y][x] = f[y-1][x] + f[y][x-1];
                }
            }
        }
        return f[n][m];

    方法2: 记忆化递归求解,耗时较长
    public:
    int uniquePaths(int m, int n) {
        if (m<0 || n<0)
            return 0;
        if (m==1 && n==1)
            return 1;
        if (memo[m][n] > 0)
            return memo[m][n];
        int left_path = uniquePaths(m-1, n);
        int up_path = uniquePaths(m, n-1);
        memo[m][n] = left_path + up_path;
        return memo[m][n];
    }
    private:
        unordered_map<int, unordered_map<int, int>> memo;

    总结:基本思路一致,就是若要求得走到(m,n)的位置,即f[m][n],只有从left和up两个方向进行考虑
    即f[m][n] = f[m-1][n] + f[m][n-1],直到终止条件为起点。

98. Validate a BST
    两种办法:
        1. 递归。通过递归在分别对左子树和右子树进行如下检查:
            初始状态:(-∞ < root.value < ∞)
            对左子树: (-∞ < root.left.value < root.val)
            对左子树:保持下界不变,改变上界值为其父节点(它的根节点)的值,判断root.left.val 是否比根节点要小,check(root.left, low, root.val)

            对右子树: (root.val < root.right.value < ∞)
            对右子树:保持上界不变,改变下界值为父节点(它的根节点)的值,
                    判断root.right.val 是否比根节点大,check(root.right, root.val, high)

        2. 中序遍历,in-order traversal

107. 层序遍历
    1. res = queue = []
    2. queue.append(root)
    3. while len(queue) != 0:
        temp = []
        quesize = len(queue)
        for i in range(quesize):
            node = queue.pop(0)
            if node.left is not None:
                queue.append(node.left)
            if node.right is not None:
                queue.append(node.right)
            temp.append(node.val)
        res.append(temp)
    4. return res

原文地址:https://www.cnblogs.com/lincs97/p/Leetcode.html

时间: 2024-08-30 15:33:10

Leetcode Notes - 刷题随笔的相关文章

LeetCode的刷题利器(伪装到老板都无法diss你没有工作)

在工程效率大行其道的今天,如果不会写点代码以后也不容易在测试圈混下去.今天给大家推荐一个LeetCode的刷题利器,可以伪装到连你老板在这里走过去都无法确认你是在干活呢,还是在干活呢. LeetCode是什么 leetcode是个题库,里面有很编程多面试的题目,可以在线编译运行.难度比较高.如果自己能都做出来,对面大公司很有帮助. 网址:https://leetcode.com/(如果对英文页面不爽的可以访问对应的中文页面:https://leetcode-cn.com/) 如果想在上面训练,首

[LeetCode] 系统刷题5_Dynamic Programming

Dynamic Programming 实际上是[LeetCode] 系统刷题4_Binary Tree & Divide and Conquer的基础上,加上记忆化的过程.就是说,如果这个题目实际上是类似于Divide and conquer或者说是DFS,但是在计算过程中有很多重复计算同样的过程的话,那么就可以用Dynamic prgramming/记忆化搜索来完成.基本就是利用空间来简化时间复杂度的过程. 可以/很有可能使用Dynamic programming的条件,满足之一即可. 1.

LeetCode开心刷题五十一天——118. Pascal&#39;s Triangle 接触跳转表概念,不知用处 lamda逗号导致表达式加法奇怪不理解119. Pascal&#39;s Triangle II

118. Pascal's Triangle Easy 87984FavoriteShare Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 5 Output: [ [1],

LeetCode开心刷题十三天——24

习惯就是人生的最大指导 ——休谟 24. Swap Nodes in Pairs Medium 1209107FavoriteShare Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. 防止用增加值,存储前后变量只进行值交换,而不处理

LeetCode开心刷题五十六天——128. Longest Consecutive Sequence

最近刷题进展尚可,但是形式变化了下,因为感觉眼睛会看瞎,所以好多写在纸上.本来想放到文件夹存储起来,但是太容易丢了,明天整理下,赶紧拍上来把 今晚是周末,这一周都在不停的学学学,我想下周怕是不能睡午觉了,中午回去床对我的诱惑太大了,我得想办法,一进门先把被褥收起来,再放个欢快的歌,中午少吃点,加油小可爱 之前欠下的烂帐,把太多简单题做完,导致剩下的都是难题,所以万万记住一点捷径都不要走 128看花花酱大神的解法,发现对hashtable的了解十分不足,甚至一些常见函数都不知道是干什么的 这道题涉

LeetCode开心刷题第四天——7逆序8字符转数字

7 Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note:Assume we are dealing with an environment which could only stor

LeetCode丨刷题历程及总结

历程 花一周左右阅读了Problem Solving with Algorithms and Data Structures Using Python,用Python实现各类数据结构和算法.此书的中文版. 2019/11/26-2020/2/2,开始刷LeetCode,按标签,通过率从高到低开始,完成218题,对标签重新归纳. 接下来整理之前做过的题目,归纳知识点和模板,还未开始. 标签整理 数据结构 数组 字符串 链表 树 字典树/二叉搜索树 线段树/线状数组 栈/队列 堆 图 拓扑排序 哈希

LeetCode日常刷题

[1] 125. 验证回文串[简单] 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写. 说明:本题中,我们将空字符串定义为有效的回文串. 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true 示例 2: 输入: "race a car" 输出: false class Solution: def isPalindrome(self, s: str) -> bool: # 回文串,

[LeetCode] 系统刷题1_代码风格及边界

代码风格 说自己不清楚的算法,比如KMP,如果解释不清楚或者写不出来的算法建议不提 注意代码的缩进以及空格的合理运用,使得代码看起来比较整洁有条理 注意边界的条件以及越界 误区: 算法想出来还仅仅不够 算法写出来也还不够 试着从面试官的角度来思考: 面试官需要多少时间review你的代码 你的coding习惯好吗 你的沟通能力怎么样 coding风格(缩进,括号,变量名) coding习惯(异常检查,边界处理) 沟通 测试(主动写出合理的test case)很重要 问自己: 你做题之前, 先在白