0213leetcode brushes 5 python questions

39

Title description:
Given an array of candidates with no repeated elements and a target number target, find out all combinations of candidates that can make the sum of numbers target.
The numbers in candidates can be repeatedly selected without limitation.

Example:
Insert picture description here
Answer:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        n = len(candidates)
        res = []
        def helper(i, tmp_sum, tmp):
            if tmp_sum > target or i == n:
                return 
            if tmp_sum == target:
                res.append(tmp)
                return 
            helper(i,  tmp_sum + candidates[i],tmp + [candidates[i]])
            helper(i+1, tmp_sum ,tmp)
        helper(0, 0, [])
        return res

224

Title description:
Implement a basic calculator to calculate the value of a simple string expression s.

Example:
Insert picture description here
Answer:

class Solution:
    def calculate(self, s: str) -> int:
        #将“(”前的和加进stack中,将“)”前的数从stack中取出和前面的和相加
        stack = []
        operator = 1
        res = 0
        num = 0
        for i in range(len(s)):
            if s[i] == '(':
                stack.append(res)
                stack.append(operator)
                res = 0
                operator = 1
                num = 0
                
            elif s[i] == ')':
                res = res + num*operator
                operator = stack.pop()
                res = stack.pop() + res*operator
                num = 0
                operator = 1
            
            elif s[i] == '+':
                res = res + num * operator
                num = 0
                operator = 1
            elif s[i] == '-':
                res = res + num * operator
                num = 0
                operator = -1
            
            elif s[i] != ' ':
                num = num*10 + int(s[i])
        res = res + num * operator
        return res      

227

Title description:
Implement a basic calculator to calculate the value of a simple string expression.
String expressions only include non-negative integers, +, -, *, / four operators and spaces. Integer division only retains the integer part.

Example:
Insert picture description here
Answer:

class Solution:
    def calculate(self, s: str) -> int:
        sign='+'
        s+="+"
        stack=[]
        num=0
        for ch in s:
            if ch>='0' and ch <='9':
                num=10*num+int(ch)
                continue

            if ch==" ":
                continue

            if sign=='+':
                stack.append(num)
            
            if sign=='-':
                stack.append(-num)

            if sign=="*":
                pre=stack.pop()
                stack.append(pre*num)
            
            if sign=='/':
                pre=stack.pop()
                stack.append(int(pre/num))
            
            sign=ch
            num=0
        
        return sum(stack)
            

576

Title description:
Given two strings s1 and s2, write a function to determine whether s2 contains the permutation of s1.
In other words, one of the permutations of the first string is a substring of the second string.

Example:
Insert picture description here
Answer:

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        l1, l2 = len(s1), len(s2)
        c1 = collections.Counter(s1)
        c2 = collections.Counter()
        cnt = 0 #统计变量,全部26个字符,频率相同的个数,当cnt==s1字母的个数的时候,就是全部符合题意,返回真
        p = q = 0 #滑动窗口[p,q]
        while q < l2:
            c2[s2[q]] += 1
            if c1[s2[q]] == c2[s2[q]]: #对于遍历到的字母,如果出现次数相同
                cnt += 1               #统计变量+1
            if cnt == len(c1):         #判断结果写在前面,此时证明s2滑动窗口和s1全部字符相同,返回真
                return True
            q += 1                     #滑动窗口右移
            if q - p + 1 > l1:         #这是构造第一个滑动窗口的特殊判断,里面内容是维护边界滑动窗口
                if c1[s2[p]] == c2[s2[p]]:    #判断性的if写在前面,因为一旦频率变化,这个统计变量就减1
                    cnt -= 1
                c2[s2[p]] -= 1                #字典哈希表移除最前面的字符
                if c2[s2[p]] == 0:            #由于counter特性,如果value为0,必须删除它
                    del c2[s2[p]]
                p += 1                        #最前面的下标右移动
        return False

703

Title description:
Design a class that finds the k-th largest element in the data stream. Note that it is the k-th largest element after sorting, not the k-th different element.
Please implement the KthLargest class:
KthLargest(int k, int[] nums) Initialize the object using integer k and integer stream nums.
int add(int val) After inserting val into the data stream nums, return the k-th largest element in the current data stream.

Example:
Insert picture description here
Answer:

class KthLargest:
    #最小堆

    def __init__(self, k: int, nums: List[int]):
        self.heap = []
        self.k = k
        for num in nums:
            heapq.heappush(self.heap,num)
            if len(self.heap) > k:
                heapq.heappop(self.heap)


    def add(self, val: int) -> int:
        heapq.heappush(self.heap,val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]




# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

Guess you like

Origin blog.csdn.net/yeqing1997/article/details/113778729