leetcode随笔VI
来源:互联网 发布:知在文言文中的意思 编辑:程序博客网 时间:2024/05/22 00:44
- leetcode题目
1.1题目描述
1.2知识点及思路
1.3代码 - 总结
一.leetcode题目
1.Factorial Trailing Zeroes
题目描述:给定一个数求其阶乘当中0的个数
知识点:观察找数学规律;二进制移位操作
思路:①找5的倍数②统计出现次数count
代码如下:
class Solution {public: int trailingZeroes(int n) { int ret=0; while(n) { ret+=n/5; n=n/5; } return ret; }};
2.Minimum Depth of Binary Tree
题目描述:求解二叉树的最小深度
知识点:树的基本概念;层次遍历;递归求解
思路:①层次遍历二叉树②遇到左右子树全为空,!temp.first->left&&!temp.first->right,则为最小深度 注:用make_pair做层次结构
参考链接:
http://blog.csdn.net/zziymt/article/details/50708255#comments
http://blog.csdn.net/sbitswc/article/details/26526031
代码如下:
/** * 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; queue<pair<TreeNode*,int>>vec; vec.push(make_pair(root,1)); while(!vec.empty()) { pair<TreeNode*,int>temp=vec.front(); vec.pop(); if(!temp.first->left&&!temp.first->right) return temp.second; if(temp.first->left) vec.push(make_pair(temp.first->left,temp.second+1)); if(temp.first->right) vec.push(make_pair(temp.first->right,temp.second+1)); } }};
python代码:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 stack,res=[(root,1)],[] while stack: p,nDepth=stack.pop() if not p.left and not p.right: res.append(nDepth) if p.right: stack.append((p.right,nDepth+1)) if p.left: stack.append((p.left,nDepth+1)) return min(res)
3.Valid Sudoku
题目描述:判断是否为数独
知识点:分治算法
思路:①遍历每行②遍历每列③遍历每个九宫格
知识扩展:回溯法(后面集中讲解)
参考代码如下:
class Solution {public://链接:hackersun007的修行之路 bool isValidSudoku(vector<vector<char>>& board) { // Note: The Solution object is instantiated only once. vector<vector<bool>> rows(9, vector<bool>(9,false)); vector<vector<bool>> cols(9, vector<bool>(9,false)); vector<vector<bool>> blocks(9, vector<bool>(9,false)); for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) { if(board[i][j] == '.')continue; int num = board[i][j] - '1'; if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num]) return false; rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true; } return true; }};
二.总结
I.方法虽同,亦需学习他人优点II.让我们一同努力,明天会更好!
1 0
- leetcode随笔VI
- vi使用随笔
- leetcode随笔
- Leetcode 随笔
- [随笔] Linux下vi命令
- leetcode随笔II
- leetcode随笔III
- leetcode随笔IV
- leetcode随笔V
- leetcode随笔VII
- leetcode随笔VIII
- Leetcode闲逛随笔
- LeetCode随笔之Array
- LeetCode随笔之栈
- LeetCode随笔之backtracking
- LeetCode随笔之Dynamic programming
- LeetCode随笔之链表
- LeetCode随笔之排序算法
- Android视图状态及重绘流程分析,带你一步步深入了解View(三)
- 重温Maven--eclipse中使用Maven
- 监听contentprovider中数据变化
- 泰勒python笔记二:正则表达式
- 支持向量机-SVM
- leetcode随笔VI
- nginx-备注
- android 4.4以上项目的选择文件和从图库中选择图片
- 3-7 关于浮动之所得
- SAP FTP上传出现的几个小问题归纳
- loadrunner11录制手机app
- 真机测试 之 证书测试
- ZSC 1568 小明的数学作业 (DFS + 模拟栈)
- python中关于深嵌元组转列表的小问题