Leetcode 2021-11-21

181. Employees Earning More Than Their Managers (Easy) SQL

Write an SQL query to find the employees who earn more than their managers.

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

SELECT
     a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
     ON a.ManagerId = b.Id
     AND a.Salary > b.Salary
;

182. Duplicate Emails (Easy) SQL


# Write your MySQL query statement below

select Email from
(
  select Email, count(Email) as num
  from Person
  group by Email
) as statistic
where num > 1
;

select Email
from Person
group by Email
having count(Email) > 1;

183. Customers Who Never Order (Easy) SQL

select name as "Customers" from Customers as c left join Orders o on c.id=o.customerId where o.id is NULL;


select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders
);

184. Department Highest Salary (Medium) SQL

# Write your MySQL query statement below
select Department,Employee,Salary from (
    select d.name as "Department", 
               e.name as "Employee",  
               e.salary as "Salary",
              rank()   OVER( partition by e.departmentId order by salary DESC) as "r"   
    from Employee as e left join Department as d on e.departmentId=d.id )
     as tmp where r=1


#answer way of writting

SELECT
    Department.name AS 'Department',
    Employee.name AS 'Employee',
    Salary
FROM
    Employee
        JOIN
    Department ON Employee.DepartmentId = Department.Id
WHERE
    (Employee.DepartmentId , Salary) IN
    (   SELECT
            DepartmentId, MAX(Salary)
        FROM
            Employee
        GROUP BY DepartmentId
    )
;

185. Department Top Three Salaries (Hard) SQL

select Department,Employee,Salary from (
    select d.name as "Department", 
               e.name as "Employee",  
               e.salary as "Salary",
              dense_rank()   OVER( partition by e.departmentId order by salary DESC) as "r"   
    from Employee as e left join Department as d on e.departmentId=d.id )
as tmp where   r<=3

#answer way of writting
SELECT
    d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary
FROM
    Employee e1
        JOIN
    Department d ON e1.DepartmentId = d.Id
WHERE
    3 > (SELECT
            COUNT(DISTINCT e2.Salary)
        FROM
            Employee e2
        WHERE
            e2.Salary > e1.Salary
                AND e1.DepartmentId = e2.DepartmentId
        )
;

186. Reverse Words in a String II (Medium)

Given a character array s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.
Your code must solve the problem in-place, i.e. without allocating extra space.

class Solution:
    def reverseWords(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        def rev(s,i,j):
            while i>=0 and j<len(s) and i<j:
                s[i],s[j]=s[j],s[i]
                i+=1
                j-=1
        
        l=0
        r=len(s)-1
        rev(s,l,r)
        start=0
        for i in range(r):
            if s[i]==' ':
                rev(s,start,i-1)
                start=i+1
        rev(s,start,r)

187. Repeated DNA Sequences (Medium)

The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.
For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is useful to identify repeated sequences within the DNA.
Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.

class Solution:
    def findRepeatedDnaSequences(self, s: str) -> List[str]:
        #sliding window s[i,i+10]  drop i add i+10, if in set, append to res
        if len(s)<=10: 
            return []
        set_ = set()
        res = set()
        for i in range(len(s)-10+1):
            cur=s[i:i+10]
            if cur in set_:
                res.add(cur)
            set_.add(cur)
        return list(res)

#
class Solution:
    def findRepeatedDnaSequences(self, s: str) -> List[str]:
        res = set()
        pos = dict()
        for i in range(len(s)-9):
            key = s[i:i+10]
            if key in pos:
                res.add(key)
            pos[key] = i
        return list(res)

188. Best Time to Buy and Sell Stock IV (Hard)

You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        #  if k==1
        if not prices: return 0
        if k==0: return 0
        min_ = [float('inf')]*k
        p_ = [float('-inf')]*k
        
        for i,n in enumerate(prices):
            min_[0] = min(min_[0],n)
            p_[0] = max(p_[0],n-min_[0])
            for j in range(1,k):
                min_[j]=min(min_[j],n-p_[j-1])
                p_[j]=max(p_[j],n-min_[j])
                

        return p_[-1]


class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:

        #two  transections
        plow = [prices[0]]*(k+1)
        res = [0]*(k+1)
        for p in prices:
            for j in range(1,k+1):
                plow[j] = min(plow[j],p-res[j-1])
                res[j] = max(res[j], p-plow[j])
        
        return res[-1]

老老实实写出K=1,K=2的情况,然后改写为数组形式。

189. Rotate Array (Medium)

Given an array, rotate the array to the right by k steps, where k is non-negative.
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
7654321
765|4321
657|1234

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l=len(nums)
        k = k%l
        def rev(nums,i,j):
            while i<j:
                nums[i],nums[j]=nums[j],nums[i]
                i+=1
                j-=1
        
        rev(nums,0,l-1)
        rev(nums,0,k-1)
        rev(nums,k,l-1)

190. Reverse Bits (Easy)

Reverse bits of a given 32 bits unsigned integer.

class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for _ in range(32):
            lastbit = n & 1
            n = n>>1
            res = res<<1 | lastbit
        return res