0214leetcode刷题5道

40

题目描述:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。

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

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        size=len(candidates)
        def helper(candidates,res,path,target,start,temp):
            for i in range(start,size):
                if candidates[i]==temp:
                    continue
                path.append(candidates[i])
                if sum(path)<target:
                    helper(candidates,res,path,target,i+1,temp)
                elif sum(path)==target:
                    res.append(path[:])
                    path.pop()
                    return
                else:
                    path.pop()
                    return
                temp=path.pop()
        res=[]
        path=[]
        temp=candidates[0]-1
        helper(candidates,res,path,target,0,temp)
        return res

119

题目描述:
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。

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

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        row = [0] * (rowIndex + 1)
        row[0] = 1
        for i in range(rowIndex):
            for j in range(i, 0, -1):
                row[j] = row[j] + row[j-1]
            row[i+1] = 1
        return row

225

题目描述:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

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

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.q=deque()


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        size = len(self.q)
        self.q.append(x)
        for _ in range(size):
            self.q.append(self.q.popleft())


    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.q.popleft()


    def top(self) -> int:
        """
        Get the top element.
        """
        return self.q[0]


    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return len(self.q)==0



# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

232

题目描述:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

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

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.instack=[]
        self.outstack=[]


    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.instack.append(x)


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if len(self.outstack) == 0:
            while self.instack:
                self.outstack.append(self.instack.pop())
        return self.outstack.pop()


    def peek(self) -> int:
        """
        Get the front element.
        """
        if len(self.outstack) == 0:
            while self.instack:
                self.outstack.append(self.instack.pop())
        return self.outstack[-1]


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.instack) == 0 and len(self.outstack) == 0



# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

剑指offer59-I

题目描述:
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。

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

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        '''
        res = []
        if not nums: 
            return res
        for i in range(len(nums)-k+1):
            res.append(max(nums[i:i+k:1]))
        return res
        '''
        # 边界条件
        if not nums:return []
        if k == 1:return nums
        if k == len(nums):return [max(nums)]
        
        # 初始化第一个窗口,求出第一个窗口的最大值
        max_tmp = max(nums[0:k])
        res = [max_tmp]
        
        # 开始滑动窗口,每滑动一次,左边抛出一个旧值,右边加入一个新值
        n = len(nums)
        for i in range(1, n - k + 1):
            old = nums[i - 1] # 左边旧值
            new = nums[i + k - 1] # 右边新值
            if old < max_tmp:# 如果抛出的旧值小于当前窗口最大值,就与加入的新值进行比较
                max_tmp = max(max_tmp, new)
            if old >= max_tmp:# 如果抛出的旧值大于等于当前窗口最大值,就重新计算当前窗口的最大值
                max_tmp = max(nums[i:i + k])
            res.append(max_tmp)
        return res

猜你喜欢

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