![](https://img-blog.csdnimg.cn/20201014180756928.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
leetcode自律
每日一题打基础
weixin_43140251
这个作者很懒,什么都没留下…
展开
-
4.20每日一题388. 文件的最长绝对路径
用栈保存每一层路径,遇到文件就比较当前路径长度和保存的最长路径长度。根据\t的个数判断路径层数,当前路径小于上一层路径就退一定次数的栈,使栈内路径和当前路径保持一致。class Solution {public: int lengthLongestPath(string input) { int ans = 0; int maxlen = 0; string tmp = ""; stack<string> path;原创 2022-04-20 21:21:01 · 354 阅读 · 0 评论 -
4.13每日一题380. O(1) 时间插入、删除和获取随机元素
很容易想到O(1)时间判断是否存在并插入删除需要用到map,O(1)时间实现随机返回要用到数组。所以就结合map和数组来实现这个类。基本思路是用map来保存val到idx的映射,在vector中按idx来保存val。需要注意的一点是remove一个元素时,不能直接在vector中erase然后改变map[val]的值,这样map[val]后面元素对应的索引不变就会出问题。举个例子:insert(100),insert(101),remove(100);第一步insert(100)的时候让map.原创 2022-04-13 13:00:12 · 259 阅读 · 0 评论 -
4.11每日一题357. 统计各位数字都不同的数字个数
题目不难,但是直接暴力搜索会超时。然后分析一下题目就知道是dp问题。n = 0时只有0一个数;即dp[0] = 1;n = 1时有0—9一共十个数;即dp[1] = 1 + 9 = 10;n>1的时候,首先有不到n位的所有结果之和,再加上n位数的结果。继续举例子,n = 2时,有dp[1] + 两位符合要求的数;考虑两位符合要求的数:第一位不能为0,即9种选择;第二位不能和第一位相同,也9种选择;所以dp[2] = 1 + 9 + 9 * 9 = 91;同理dp[3] = 9原创 2022-04-11 12:31:38 · 203 阅读 · 0 评论 -
4.10每日一题420. 强密码检验器
class Solution {public: int max(int a, int b){ return a > b ? a : b; } int strongPasswordChecker(string password) { int ans = 0; int k = 0; int l = password.length(); map<string, int> type; .原创 2022-04-10 14:28:55 · 301 阅读 · 0 评论 -
4.8每日一题429. N 叉树的层序遍历
输入数据很奇怪,明明是node节点,但是给的参考输入是数组,不过无所谓,按节点来做就行。/*// Definition for a Node.class Node {public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children)原创 2022-04-08 13:22:56 · 234 阅读 · 0 评论 -
4.6每日一题 310. 最小高度树
暴力方法直接每个点当头节点dfs一下,保留每个节点开始的高度,输出最小的,比较容易想,但是超时了。。。然后参考了答案,发现很好的思路:求路径最长的路:证明在一篇论文里:http://courses.csail.mit.edu/6.046/fall01/handouts/ps9sol.pdf完整代码:class Solution {public: int findLongestNode(int u, vector<int> & parent, vector<vec原创 2022-04-06 14:02:42 · 240 阅读 · 0 评论 -
4.4每日一题(线段树)307. 区域和检索 - 数组可修改
先想到暴力解法直接用数组保留前i项和,求sumRange可以直接做差,但是发现会超时。后来想到分块,和暴力求法类似,AC。class NumArray {public: vector<int> sums; vector<int> &nums; int s; NumArray(vector<int>& nums) : nums(nums){ int n = nums.size(); s =原创 2022-04-04 10:20:43 · 164 阅读 · 0 评论 -
3.28每日一题(位运算)693.交替位二进制数
只想到了可以原地计算class Solution {public: bool hasAlternatingBits(int n) { int tmp = n % 2; n /= 2; while(n){ if(n % 2 == tmp) return false; tmp = n % 2; n /= 2; } re原创 2022-03-28 12:47:24 · 294 阅读 · 2 评论 -
3.23每日一题440字典序的第k小数字
3.23每日一题有点难,看了题解想到的思想是看作一个树,先序遍历即为要求的字典序class Solution {public: int getpointnum(int curr, int n){ //first和last保存这一个节点的每一层的头节点和尾节点 long first = curr; long last = curr; //pointnum保存搜索到了多少个节点 int pointnum = 0;原创 2022-03-23 15:25:11 · 93 阅读 · 0 评论