✅ 965. 单值二叉树

https://leetcode-cn.com/problems/univalued-binary-tree/

描述

如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。

只有给定的树是单值二叉树时,才返回 true;否则返回 false。

解答

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:
bool isUnivalTree(TreeNode* root) {
int markfirst = root->val;
std::queue<TreeNode* > q;
q.push(root); while(!q.empty()){
TreeNode* tmp = q.front();
if (tmp->val != markfirst) return false;
else {
q.pop();
if(tmp->left != NULL){
q.push(tmp->left);
}
if(tmp->right != NULL){
q.push(tmp->right);
}
}
}
return true;
}
}; /*执行用时 :
12 ms
, 在所有 C++ 提交中击败了
30.77%
的用户
内存消耗 :
10.7 MB
, 在所有 C++ 提交中击败了
26.52%
的用户*/

updated dfs 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:
bool dfs(TreeNode *root, int val) {
if(!root){
return true;
}
if(root->val != val) return false;
return dfs(root->left, val) && dfs(root->right, val);
}
bool isUnivalTree(TreeNode* root) {
if(!root) return true;
int mark1st = root->val;
return dfs(root, mark1st);
}
}; /*执行用时 :
8 ms
, 在所有 C++ 提交中击败了
30.77%
的用户
内存消耗 :
10.7 MB
, 在所有 C++ 提交中击败了
9.98%
的用户*/

py

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def __init__(self):
self.res = set()
def isUnivalTree(self, root: TreeNode) -> bool:
if root is None:
return
self.res.add(root.val)
self.isUnivalTree(root.left)
self.isUnivalTree(root.right)
return len(self.res) == 1
'''
执行用时 :
28 ms
, 在所有 Python3 提交中击败了
93.25%
的用户
内存消耗 :
13 MB
, 在所有 Python3 提交中击败了
46.72%
的用户
'''

py 生成器

生成器大法好

class Solution(object):
def isUnivalTree(self, root):
root = iterable(root)
return len(set(root)) == 1 def iterable(p):
if p:
yield p.val
yield from iterable(p.left)
yield from iterable(p.right)

✅ 762. 二进制表示中质数个计算置位

https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation/

描述

给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。

(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)

示例 1:

输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)

解答

cpp other

class Solution {
public:
int countPrimeSetBits(int L, int R) {
int count = 0;
for (int i = L;i <= R;i++) {
if (isPrime(countCore(i))) count++;
} return count;
} int countCore(int num) {
int count = 0;
while (num) {
num &= (num - 1);
count++;
} return count;
} bool isPrime(int num) {
if (num == 2) return true;
// 除2以外的其余偶数
if (num == 1 || (num & 0x1) == 0) return false; for (int i = 3;i <= sqrt(num);i+=2) {
if (num % i == 0) return false;
} return true;
}
}; --- class Solution {
public:
int countPrimeSetBits(int L, int R) {
set<int>prime_num = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
int cnt = 0;
for(int i=L; i<=R; i++)
{
bitset<32>num(i);
if(prime_num.count(num.count()) == 1)
cnt ++;
}
return cnt;
}
};

cpp mine

class Solution {
public:
int countPrimeSetBits(int L, int R) {
set<int> allThePrimeNums = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
int cnt = 0;
for (int i = L; i <= R; i++) {
bitset<32> num(i);
if(allThePrimeNums.count(num.count()) == 1) cnt++;
}
return cnt;
}
};
/*执行用时 :
16 ms
, 在所有 C++ 提交中击败了
70.86%
的用户
内存消耗 :
8.7 MB
, 在所有 C++ 提交中击败了
5.47%
的用户*/

java isPrime 高效写法,copy me!

    private boolean isPrimeNum(int i) {
for (int j = i == 2 ? 3 : 2; j <= Math.sqrt(i) + 1; j++) {
if (i % j == 0) return false;
}
return true;
}

py

class Solution:
def countPrimeSetBits(self, L: int, R: int) -> int:
temp = [2, 3, 5, 7, 11, 13, 17, 19]
return len([i for i in range(L, R+1) if bin(i).count('1') in temp])
'''
执行用时 :
248 ms
, 在所有 Python3 提交中击败了
73.46%
的用户
内存消耗 :
13.1 MB
, 在所有 Python3 提交中击败了
52.38%
的用户
'''

✅ 1047. 删除字符串中的所有相邻重复项

https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/

描述

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

 

示例:

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

解答

c++ other

class Solution {
public:
string removeDuplicates(string S) {
int top = 0;
for (char ch : S) {
if (top == 0 || S[top - 1] != ch) {
S[top++] = ch;
} else {
top--;
}
}
S.resize(top);
return S;
}
};
// 模拟一遍了,发现真NB ⬆️
// copy me ⬇️ todo 0214
class Solution {
public:
string removeDuplicates(string S) {
deque<char> q;
for(int i=0;i<S.size();i++){
if(!q.empty()&&q.back()==S[i])
q.pop_back();
else
q.push_back(S[i]);
}
string ans = "";
while(!q.empty())
{
ans.push_back(q.front());
q.pop_front();
}
return ans;
}
};

py


'''
方法一:替换函数
我们可以用字符串自带的替换函数,由于字符串仅包含小写字母,因此只有 26 种不同的重复项。 将 aa 到 zz 的 26 种重复项放入集合中; 遍历这 26 种重复项,并用字符串的替换函数把重复项替换成空串。 注意,在进行过一次替换之后,可能会出现新的重复项。例如对于字符串 abbaca,如果替换了重复项 bb,字符串会变为 aaca,出现了新的重复项 aa。因此,上面的过程需要背重复若干次,直到字符串在一整轮替换过程后保持不变(即长度不变)为止。 '''
from string import ascii_lowercase
class Solution:
def removeDuplicates(self, S: str) -> str:
# generate 26 possible duplicates
duplicates = {2 * ch for ch in ascii_lowercase} prev_length = -1
while prev_length != len(S):
prev_length = len(S)
for d in duplicates:
S = S.replace(d, '') return S
'''
方法二:栈
我们可以用栈来维护没有重复项的字母序列: 若当前的字母和栈顶的字母相同,则弹出栈顶的字母; 若当前的字母和栈顶的字母不同,则放入当前的字母。
''' class Solution:
def removeDuplicates(self, S: str) -> str:
output = []
for ch in S:
if output and ch == output[-1]:
output.pop()
else:
output.append(ch)
return ''.join(output)

模仿上面的py 的c++ 代码出错了:todo 0214

到底是 不会很精确的c++ api

#include <algorithm>
class Solution {
public:
string removeDuplicates(string S) {
stack<char> ss;
for(char ch: S) {
if(&ss != NULL && (ch == ss.top())) {
ss.pop();
}
else {
ss.push(ch);
}
}
char *ret = "";
int i = 0;
printf("ss size: %d", ss.size());
while(!ss.empty()){
if(ss.top()){
ret[i++] = ss.pop();
}
}
ret[i] = '\0';
reverse(ret[0], ret[i-1]);
return ret;
}
}; /*编译出错solution.cpp: In member function removeDuplicates
Line 19: Char 33: error: void value not ignored as it ought to be
ret[i++] = ss.pop();
^*/

✅ 171. Excel表列序号(26进制转10进制)

https://leetcode-cn.com/problems/excel-sheet-column-number/

描述

给定一个Excel表格中的列名称,返回其相应的列序号。

例如,

    A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1: 输入: "A"
输出: 1
示例 2: 输入: "AB"
输出: 28

解答

26进制转10进制

c

class Solution {
public:
int titleToNumber(string s) {
int ret = 0;// you must init local var to 0; while global var can auto init to 0
for (int i = 0; i < s.size(); i++) {
ret = ret * 26 + (s[i] - 'A' + 1);
}
return ret;
}
};

java


py

class Solution:
def titleToNumber(self, s: str) -> int:
ans = 0;
for ch in s:
ans *= 26;
ans += ord(ch) - ord('A') + 1
return ans
'''
几秒前 通过 36 ms 13.1 MB Python3
几秒前 通过 4 ms 8.2 MB Cpp
'''

leetcode 0214的更多相关文章

  1. leetcode 0211

    目录 ✅ 1217. 玩筹码 描述 解答 c java py ✅ 206. 反转链表 描述 解答 c java py ✅ 922. 按奇偶排序数组 II 描述 解答 c 双指针soldier tddo ...

  2. 【LeetCode】LCP 07. 传递信息

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 日期 题目地址:https://leetcod ...

  3. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  4. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  5. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  6. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  7. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  8. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  9. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

随机推荐

  1. JavaScript.Array.some() 方法用法

    定义和用法:some() 方法用于检测数组中的元素是否满足指定条件(函数提供). some() 方法会依次执行数组的每个元素: 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检 ...

  2. MyBatis(3)——配置解析

    MyBatis中文参考指南:MyBatis用户指南 //------------核心配置文件说明------------// //*在注释中进行说明 <configuration> < ...

  3. Nginx的相关介绍

    前言 说到服务器,一定会想到apache的httpd和Nginx Apache的发展时期很长,而且是毫无争议的世界第一大服务器.它有着很多优点:稳定.开源.跨平台等等.它出现的时间太长了,它兴起的年代 ...

  4. 高斯消元-bzoj1013-球形空间产生器

    This article is made by Jason-Cow.Welcome to reprint.But please post the writer's address. http://ww ...

  5. JetBrains PyCharm 2018.2.1 x64永久激活码

    812LFWMRSH-eyJsaWNlbnNlSWQiOiI4MTJMRldNUlNIIiwibGljZW5zZWVOYW1lIjoi5q2j54mIIOaOiOadgyIsImFzc2lnbmVlT ...

  6. leetcode 25. K 个一组翻转链表

    # coding:utf-8 __author__ = "sn" """ 25. K 个一组翻转链表 给你一个链表,每 k 个节点一组进行翻转,请你返 ...

  7. drf框架,restful接口规范,源码分析

    复习 """ 1.vue如果控制html 在html中设置挂载点.导入vue.js环境.创建Vue对象与挂载点绑定 2.vue是渐进式js框架 3.vue指令 {{ }} ...

  8. 【资源分享】Half-Life(半条命)中英版

    *----------------------------------------------[下载区]----------------------------------------------* ...

  9. 如何在Linux中显示和设置主机名(适用ubantu、centos等版本)

    随着连接到网络的计算机数量越来越多,每一台计算机都需要有一个属性来区别于其它计算机.和现实世界中的人一样,计算机也有一个叫做hostname(主机名)的属性. 什么是hostname 从它的操作手册来 ...

  10. C++子类虚函数表指针

    最近看剑指offer,记录一下 #include <iostream> #include <string> #include <cctype> #include&l ...