leetcode题解日练--2016.6.24

2024-03-06 10:48
文章标签 leetcode 24 题解 日练 2016.6

本文主要是介绍leetcode题解日练--2016.6.24,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

编程日记,尽量保证每天至少3道leetcode题,仅此记录学习的一些题目答案与思路,尽量用多种思路来分析解决问题,不足之处还望指出。标红题为之后还需要再看的题目。

今日题目:1、求二叉树和为sum的路径;2、判断数组是否合法;3、求二叉树的最小深度。

26. 112. Path Sum | Difficulty: Easy

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
题意:给定一棵二叉树与一个sum值,求一条从根节点到叶节点的路径。
思路:
1、很容易用递归的思想去思考这个问题,递归的话当然就是找终止条件了。失败的终止条件是root为NULL,而成功找到的终止条件是root节点的值恰好是sum剩下的值并且左右均无子节点。当前既不成功也不失败就递归去判断这个点的左节点和右节点是否有一个满足,注意此时sum应该减去root->val的值。
代码:
递归版

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:bool hasPathSum(TreeNode* root, int sum) {if(root==NULL )    return false;if(root->val==sum && root->left==NULL && root->right==NULL) return true;return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);}
};

结果:12ms
2、将上述递归版本改为迭代版本。先将最左路的元素加入到一个栈中,如果不满足依次去访问这个栈中的元素的右子路径,访问右路径的策略是先将右路的最左路加入,然后和之前的步骤一样。

class Solution {
public:bool hasPathSum(TreeNode *root, int sum) {//后序遍历stack<TreeNode *> s;//pre节点表示当前节点的上一个节点,为空代表当前节点是第一个节点,没有上一个节点TreeNode *pre = NULL, *cur = root;int SUM = 0;//首先将cur设置为当前树的最左路节点while (cur || !s.empty()) {while (cur) {s.push(cur);SUM += cur->val;cur = cur->left;}cur = s.top();//如果此时在cur已经满足了路径和为sum并且无左右节点的条件,则返回为真if (cur->left == NULL && cur->right == NULL && SUM == sum) {return true;}//如果当前节点有右节点并且它的右节点并没有访问过,那么就去访问cur的右节点if (cur->right && pre != cur->right) {cur = cur->right;//如果右节点访问过了或者当前节点并没有右节点} else {pre = cur;s.pop();SUM -= cur->val;cur = NULL;}}return false;}
};

结果:15ms,为什么时间反而更多?
这段代码还不熟悉,之后还需要再看。

36. Valid Sudoku | Difficulty: Easy

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
题意:验证一个数独是否有效,有效不代表有解,只要填充部分不冲突即视为有效。什么是冲突?就是每一行、每一列、每一个小方格只能包含1-9各一个。
思路:
1、依次判断每一行、每一列、每一方格的元素是否合法
c++

class Solution {
public:bool isValidSudoku(vector<vector<char>>& board) {int cnt[9] = {0};//首先判断每行for(int i=0;i<9;i++){for(int j=0;j<9;j++){   if(board[i][j]=='.')continue;cnt[(int)(board[i][j]-'1')]++;}for (int idx = 0;idx<9;idx++){if (cnt[idx]>1)return false;elsecnt[idx]=0;}}//再判断每列for(int j=0;j<9;j++){for(int i=0;i<9;i++){   if(board[i][j]=='.')continue;cnt[(int)(board[i][j]-'1')] ++;}for (int idx = 0;idx<9;idx++){if (cnt[idx]>1)return false;elsecnt[idx]=0;}}//判断每一个小格子for(int k=0;k<9;k++){for(int i=3*(k/3);i<3*(k/3)+3;i++){   for(int j=3*(k%3);j<3*(k%3)+3;j++){if(board[i][j]=='.')continue;cnt[(int)(board[i][j]-'1')] ++;}}for (int idx = 0;idx<9;idx++){if (cnt[idx]>1)return false;elsecnt[idx]=0;}}return true;}
};

结果:16ms

2、创建三个数组用来保存状态,一个储存行信息,一个储存列信息,一个储存块信息。
rows[i][j] 是指的数字(j+1)在第i行出现的次数
cols[i][j] 是指的数字(j+1)在第i行出现的次数
blocks[i][j][k]是指的数字(k+1)在第(i,j)个小块中出现的次数

class Solution {
public:bool isValidSudoku(vector<vector<char>>& board) {int rows[9][9]={0}; //rows[i][j] 是指的数字(j+1)在第i行出现的次数int cols[9][9]={0}; //cols[i][j] 是指的数字(j+1)在第i行出现的次数int blocks[3][3][9]={0};//blocks[i][j][k]是指的数字(k+1)在第(i,j)个小块中出现的次数for(int row=0;row<9;row++)    //row代表行,col代表列,遍历一次for(int col=0;col<9;col++)if(board[row][col]!='.'){   //跳过'.'int number=board[row][col]-'1'; //将字符转换位数字0-8if(rows[row][number]++) return false; //如果数字number在第row行第二次出现if(cols[col][number]++) return false;//如果数字number在第col列第二次出现if(blocks[row/3][col/3][number]++) return false;//如果数字number在第(row/3,col/3)个小块第二次出现}return true;}
};

111. Minimum Depth of Binary Tree | Difficulty: Easy

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

题意:求二叉树的最小深度,但是必须是从根节点到叶节点,不能是根节点直接到空节点。
思路:与最大深度类似,最小深度只要再多加一次判断子树是否为空就可以写出递归版本的代码。
代码:
C++

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int minDepth(TreeNode *root) {if(!root) return 0;if(!root->left) return 1 + minDepth(root->right);if(!root->right) return 1 + minDepth(root->left);return 1+min(minDepth(root->left),minDepth(root->right));}
};

结果:12ms

2、BFS的思想,从根节点开始判断,逐层进行判断,一但满足该节点是叶子节点返回当前节点的深度。
c++

class Solution {
public:int minDepth(TreeNode *root) {if (root==NULL) return 0;queue <TreeNode*> nodes;TreeNode* tmp;nodes.push(root);int depth = 0;while(!nodes.empty()){depth++;int size = nodes.size();for(int i=0;i<size;i++){tmp = nodes.front();if(tmp->left==NULL && tmp->right==NULL)    return depth;if(tmp->left) nodes.push(tmp->left);if(tmp->right) nodes.push(tmp->right);nodes.pop();}}return 0;  }
};

结果:12ms

这篇关于leetcode题解日练--2016.6.24的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/779819

相关文章

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【JavaScript】LeetCode:16-20

文章目录 16 无重复字符的最长字串17 找到字符串中所有字母异位词18 和为K的子数组19 滑动窗口最大值20 最小覆盖字串 16 无重复字符的最长字串 滑动窗口 + 哈希表这里用哈希集合Set()实现。左指针i,右指针j,从头遍历数组,若j指针指向的元素不在set中,则加入该元素,否则更新结果res,删除集合中i指针指向的元素,进入下一轮循环。 /*** @param

C - Word Ladder题解

C - Word Ladder 题解 解题思路: 先输入两个字符串S 和t 然后在S和T中寻找有多少个字符不同的个数(也就是需要变换多少次) 开始替换时: tips: 字符串下标以0开始 我们定义两个变量a和b,用于记录当前遍历到的字符 首先是判断:如果这时a已经==b了,那么就跳过,不用管; 如果a大于b的话:那么我们就让s中的第i项替换成b,接着就直接输出S就行了。 这样

LeetCode:64. 最大正方形 动态规划 时间复杂度O(nm)

64. 最大正方形 题目链接 题目描述 给定一个由 0 和 1 组成的二维矩阵,找出只包含 1 的最大正方形,并返回其面积。 示例1: 输入: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0输出: 4 示例2: 输入: 0 1 1 0 01 1 1 1 11 1 1 1 11 1 1 1 1输出: 9 解题思路 这道题的思路是使用动态规划

【秋招笔试】9.07米哈游秋招改编题-三语言题解

🍭 大家好这里是 春秋招笔试突围,一起备战大厂笔试 💻 ACM金牌团队🏅️ | 多次AK大厂笔试 | 大厂实习经历 ✨ 本系列打算持续跟新 春秋招笔试题 👏 感谢大家的订阅➕ 和 喜欢💗 和 手里的小花花🌸 ✨ 笔试合集传送们 -> 🧷春秋招笔试合集 🍒 本专栏已收集 100+ 套笔试题,笔试真题 会在第一时间跟新 🍄 题面描述等均已改编,如果和你笔试题看到的题面描述