leetcode 0208

目录

  • ? 108. 将有序数组转换为二叉搜索树

    • 描述
    • 解答
      • py
      • 【todo rev 0208】py知识:if not x:if x is not None:if not x is None:使用
  • ? 344. 反转字符串
    • 描述
    • 解答
  • ? 944. 删列造序
    • 描述
    • 解答
      • when you use py: using zip
      • when u use c: dive deep into 2d array
  • ? 181. 超过经理收入的员工
    • 描述
    • 解答
      • sql 的 as

? 108. 将有序数组转换为二叉搜索树

https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

描述

解答

py

错在: Python没有三目运算符(?:),类函数不可调用

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        return nums == null ? null : buildTree(nums, 0, nums.len)#tt Python没有三目运算符(?:)
    #tt 而且py 自己定义的函数,也不是 像java 那里可以调用同 类 中的函数
    def buildTree(nums: List[int], l: int, r: int) -> TreeNode:
        if(l > r):
            return null;
        m = l + (r - l) / 2
        root = nums[m]
        root.left = buildTree(nums, l, m - 1)
        root.right = buildTree(nums, m + 1, r)
        return root

fix:

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if not nums: # 注意要使用if not ,而不是 if nums == None
            return None
        else:
            mid = len(nums) // 2;
            tn = TreeNode(nums[mid])
            nums1 = nums[0:mid]
            nums2 = nums[mid+1: len(nums)]
            tn.left = self.sortedArrayToBST(nums1)
            tn.right = self.sortedArrayToBST(nums2)
        return tn

'''执行用时 :
100 ms
, 在所有 Python3 提交中击败了
16.13%
的用户
内存消耗 :
15.4 MB
, 在所有 Python3 提交中击败了
49.31%
的用户'''

【todo rev 0208】py知识:if not x:if x is not None:if not x is None:使用

https://blog.csdn.net/sasoritattoo/article/details/12451359

代码中经常会有变量是否为None的判断,有三种主要的写法:

?第一种是if x is None

第二种是 if not x:

第三种是if not x is None(这句这样理解更清晰if not (x is None)) 。

如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:


>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即:

not None == not False == not '' == not 0 == not [] == not {} == not ()

因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时if not x:将会出现问题:

>>> x = []
>>> y = None
>>>
>>> x is None
False
>>> y is None
True
>>>
>>>
>>> not x
True
>>> not y
True
>>>
>>>
>>> not x is None
>>> True
>>> not y is None
False
>>> 

也许你是想判断x是否为None,但是却把x==[]的情况也判断进来了,此种情况下将无法区分。
对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None, ?False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。?

而对于if x is not Noneif not x is None写法,很明显前者更清晰,而后者有可能使读者误解为if (not x) is None,因此推荐前者,同时这也是谷歌推荐的风格

结论:

if x is not None是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

使用if not x这种写法的前提是:必须清楚x等于None, ?False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。


? 344. 反转字符串

https://leetcode-cn.com/problems/reverse-string

描述

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

示例 1:

输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

解答

以下的 range() 这些函数 真的就是肌肉写的,无脑记忆写的,猜的。

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        for i in range(len(s) // 2):
            c = s[i]
            s[i] = s[len(s) - 1 - i]
            s[len(s) - 1 - i] = c

其实,幸亏 range 函数是 右边 开的:

>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

所以,当len(s) == 4, we have len(s) // 2 == 2, but using range(2) will result: [0, 1], notice there has no 2, so it‘s safe, cause we dont swap s[2] and s[1] (after we swapped s[1] with s[2]

? 944. 删列造序

https://leetcode-cn.com/problems/delete-columns-to-make-sorted

描述

解答

我的理解是,找到所有不 合适 的列,每找到 一个,就 cnt++

所以 重点是,如何在 矩阵中 的列 进行遍历

when you use py: using zip

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        ret = 0
        for i in zip(*A):#success, use: zip(A) will fail, so what is * means for a list???
            if list(i) != sorted(i):
                ret += 1
        return ret

'''执行用时 :
92 ms
, 在所有 Python3 提交中击败了
94.28%
的用户
内存消耗 :
13.7 MB
, 在所有 Python3 提交中击败了
50.69%
的用户'''

python zip

描述:

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 *号操作符,可以将元组解压为列表。

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip()返回的是一个对象。如需展示列表,需手动 list() 转换。

eg in py2:
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
eg in py3
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]

>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

when u use c: dive deep into 2d array

int minDeletionSize(char** A, int ASize) {
    int count = 0;
    for(int i = 0;i < strlen(A[0]);i++){
        for(int j = 0;j < ASize - 1;j++){
            if(A[j][i] > A[j+1][i]){
                count++;
                break;
            }
        }
    }
    return count;
}

'''---

my '''

int minDeletionSize(char ** A, int ASize){
    int cnt = 0;
    int i = 0;
    int j = 0;
    int colNum = 0;
    colNum = strlen(A[0]);
    printf("colNum is %d", colNum);
    for(; i < colNum; i++){
        for(j = 0; j < ASize - 1; j++){
            if(A[j][i] > A[j + 1][i]){
                cnt++;
                break;// only break inner for-loop
            }
        }
    }
    return cnt;
}

/*执行用时 :
32 ms
, 在所有 C 提交中击败了
26.53%
的用户
内存消耗 :
9.3 MB
, 在所有 C 提交中击败了
57.43%
的用户*/

? 181. 超过经理收入的员工

https://leetcode-cn.com/problems/employees-earning-more-than-their-managers

描述

Employee?表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+
给定?Employee?表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

+----------+
| Employee |
+----------+
| Joe      |
+----------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答

select e1.Name as Employee from Employee as e1 ,Employee as e2 where e1.ManagerId=e2.Id AND e1.Salary>e2.Salary

”和自己的xxx比”这种问题基本都是自连接问题。

SELECT E1.Name AS Employee FROM Employee as E1,Employee as E2
WHERE E1.ManagerId=E2.Id AND E1.Salary>E2.Salary;

疑问是: E1,Employee as E2 这里, select xxx from Table, WTF clause here

sql 的 as

as 后面跟着的 是一个别名



正常来说,想查询该表,那么sql语句如下

select * from user

给别人看,自然是需要很多的时间来理解和熟悉,那么as的作用就提现出来了

select
     username as 账号 ,
     password as 密码,
     mingzi as 名字,
    zhengjianhao as 证件号,
    dianhua as 电话,
    zhuceriqi as 注册日期,
    zhuangtai as 状态,
    quanxian as 权限,
    shengyutianshu as 剩余天数
     from user

as 后面跟着的 是一个别名

【todo 理解 sql as 0208】


# Write your MySQL query statement below
SELECT
    Name Employee # wtf  Employee 可是 表名啊!!!
FROM
    Employee AS a
WHERE
    Salary > (SELECT
            Salary
        FROM
            Employee
        WHERE
            Id = a.Managerid)

我认为, 这个官方的答案 令人满意 清晰了:

https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/solution/chao-guo-jing-li-shou-ru-de-yuan-gong-by-leetcode/


SELECT
    *
FROM
    Employee AS a,
    Employee AS b
WHERE
    a.ManagerId = b.Id
        AND a.Salary > b.Salary
;

---imp:(cause we only need `name`)

SELECT
    a.Name AS 'Employee'
FROM
    Employee AS a,
    Employee AS b
WHERE
    a.ManagerId = b.Id
        AND a.Salary > b.Salary
;

原文地址:https://www.cnblogs.com/paulkg12/p/12276013.html

时间: 2024-07-30 16:01:23

leetcode 0208的相关文章

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,

LeetCode OJ - Sum Root to Leaf Numbers

这道题也很简单,只要把二叉树按照宽度优先的策略遍历一遍,就可以解决问题,采用递归方法越是简单. 下面是AC代码: 1 /** 2 * Sum Root to Leaf Numbers 3 * 采用递归的方法,宽度遍历 4 */ 5 int result=0; 6 public int sumNumbers(TreeNode root){ 7 8 bFSearch(root,0); 9 return result; 10 } 11 private void bFSearch(TreeNode ro

LeetCode OJ - Longest Consecutive Sequence

这道题中要求时间复杂度为O(n),首先我们可以知道的是,如果先对数组排序再计算其最长连续序列的时间复杂度是O(nlogn),所以不能用排序的方法.我一开始想是不是应该用动态规划来解,发现其并不符合动态规划的特征.最后采用类似于LRU_Cache中出现的数据结构(集快速查询和顺序遍历两大优点于一身)来解决问题.具体来说其数据结构是HashMap<Integer,LNode>,key是数组中的元素,所有连续的元素可以通过LNode的next指针相连起来. 总体思路是,顺序遍历输入的数组元素,对每个

LeetCode OJ - Surrounded Regions

我觉得这道题和传统的用动规或者贪心等算法的题目不同.按照题目的意思,就是将被'X'围绕的'O'区域找出来,然后覆盖成'X'. 那问题就变成两个子问题: 1. 找到'O'区域,可能有多个区域,每个区域'O'都是相连的: 2. 判断'O'区域是否是被'X'包围. 我采用树的宽度遍历的方法,找到每一个'O'区域,并为每个区域设置一个value值,为0或者1,1表示是被'X'包围,0则表示不是.是否被'X'包围就是看'O'区域的边界是否是在2D数组的边界上. 下面是具体的AC代码: class Boar

LeetCode 10. Regular Expression Matching

https://leetcode.com/problems/regular-expression-matching/description/ Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover

(leetcode题解)Pascal&#39;s Triangle

Pascal's Triangle  Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 题意实现一个杨辉三角. 这道题只要注意了边界条件应该很好实现出来,C++实现如下 vector<vector<int>> generate(int

[LeetCode]Count Primes

题目:Count Primes 统计1-n的素数的个数. 思路1: 通常的思想就是遍历(0,n)范围内的所有数,对每个数i再遍历(0,sqrt(i)),每个除一遍来判断是否为素数,这样时间复杂度为O(n*sqrt(n)). 具体实现不在贴代码,过程很简单,两重循环就可以解决.但是效率很差,n较大时甚至会花几分钟才能跑完. 思路2: 用埃拉特斯特尼筛法的方法来求素数,时间复杂度可以达到O(nloglogn). 首先开一个大小为n的数组prime[],从2开始循环,找到一个质数后开始筛选出所有非素数

[LeetCode]Repeated DNA Sequences

题目:Repeated DNA Sequences 给定包含A.C.G.T四个字符的字符串找出其中十个字符的重复子串. 思路: 首先,string中只有ACGT四个字符,因此可以将string看成是1,3,7,20这三个数字的组合串: 并且可以发现{ACGT}%5={1,3,2,0};于是可以用两个位就能表示上面的四个字符: 同时,一个子序列有10个字符,一共需要20bit,即int型数据类型就能表示一个子序列: 这样可以使用计数排序的思想来统计重复子序列: 这个思路时间复杂度只有O(n),但是