leetcode 0214

✅ 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
'''

posted on 2020-02-14 12:03  Paulkg12  阅读(281)  评论(0编辑  收藏  举报

导航