0213leetcode刷题5道python

39

题目描述:
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。

示例:
在这里插入图片描述
解答:

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

题目描述:
实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。

示例:
在这里插入图片描述
解答:

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

题目描述:
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。

示例:
在这里插入图片描述
解答:

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

题目描述:
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。

示例:
在这里插入图片描述
解答:

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

题目描述:
设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。

示例:
在这里插入图片描述
解答:

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)

猜你喜欢

转载自blog.csdn.net/yeqing1997/article/details/113778729