码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 简单题

时间:2019-04-09 20:36:32      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:element   ace   initial   add   enumerate   push   struct   利用   turn   

  1. (leetcode 703) 数据流中的第k大元素

    利用小顶堆

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.size = len(nums)
        self.nums = nums
        heapq.heapify(self.nums)
        while self.size > k:
            heapq.heappop(self.nums)
            self.size -= 1
            
    def add(self, val: int) -> int:
        if self.size < self.k:
            heapq.heappush(self.nums,val)
            self.size += 1
        elif val > self.nums[0]:
            heapq.heapreplace(self.nums,val)
        return self.nums[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

  1. leetcode 20 有效的括号
class Solution:
    def isValid(self, s: str) -> bool:
        if not str:
            return True
        s_dict = {"(":")","{":"}","[":"]"}
        que = []
        for v in s:
            if len(que) > 0:
                if s_dict[que[-1]] == v:
                    que.pop()
                else:
                    if v in s_dict.values():
                        return False
                    que.append(v)
            else:
                if v in s_dict.values():
                    return False
                que.append(v)
        if len(que) ==0:
            return True
        else:
            return False
  1. (leetcode 155)最小栈
class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.order = []
        self.min = float('inf')
        self.secMin = float('inf')
        self.size = 0
    def push(self, x: int) -> None:
        self.stack.append(x)
        self.size += 1
        self.order = sorted(self.stack)
    def pop(self) -> None:
        if self.size == 0:
            return None
        indx = self.order.index(self.stack[-1])
        del self.stack[-1]
        del self.order[indx]
        self.size -= 1

    def top(self) -> int:
        if self.size == 0:
            return None
        return self.stack[-1]
    def getMin(self) -> int:
        if self.size == 0:
            return None
        return self.order[0]
  1. (leetcode 225) 队列实现栈
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stacks = []
        self.size = 0
        

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.stacks.append(x)
        self.size += 1

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        re = self.stacks[-1]
        del self.stacks[-1]
        self.size -= 1
        return re
    def top(self) -> int:
        """
        Get the top element.
        """
        return self.stacks[-1]
        

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if self.size == 0:
            return True
        return False
  1. (leetcode 496) 下一个更大的元素
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = []
        for v in nums1:
            flag = 0
            indx = nums2.index(v)
            for m in nums2[indx:]:
                if m > v:
                    result.append(m)
                    flag = 1
                    break
            if not flag:
                result.append(-1)
        return result
  1. (leetcode 682) 棒球比赛

    注:题目,思路都很简单,注意要把字符变成数字

class Solution:
    def calPoints(self, ops: List[str]) -> int:
        que = []
        for v in ops:
            if v == "C":
                if len(que) > 0:
                    que.pop()
            else:
                if v != "+" and v!= "D":
                    que.append(int(v))
                else:
                    que.append(v)
            
        for i,v in enumerate(que):
            if v == "+":
                if i == 0:
                    que[i] = 0
                else:
                    tmp = i-2 if i >2 else 0
                    que[i] = sum(que[tmp:i])
            elif v == "D":
                if i>0:
                    que[i] = 2* que[i-1]
                else:
                    que[i] = 0
        sumr = 0
        for v in que:
            sumr += v
        return sumr
  1. (leetcode 232) 用栈实现队列
class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.que = []
        self.size = 0
        

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.que.append(x)
        self.size += 1

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        tmp = self.que[0]
        del self.que[0]
        self.size -= 1
        return tmp

    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.que[0]
        

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if self.size ==0:
            return True
        return False
  1. (leetcode 884) 比较含退格的字符串
class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        
        def delStr(s):
            s1 = []
            for v in s:
                if v == "#":
                    if len(s1) > 0:
                        s1.pop()
                else:
                    s1.append(v)
            return s1
        
        s1 = delStr(S)
        t1 = delStr(T)
        if s1 == t1:
            return True
        return False

贪心算法

  1. (leetcode 122) 买卖股票的最佳时机
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        sumr = 0
        if len(prices) == 0:
            return 0
        for i in range(1,len(prices)):
            tmp = prices[i] - prices[i-1]
            if tmp > 0:
                sumr += tmp
        return sumr
  1. (leetcode 455) 分发饼干
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        
        def findIndex(val,indx):
            flag = 0
            for i in range(indx,len(orderS)):
                if orderS[i] >= val:
                    return i
            return len(orderS)
        
        orderG = sorted(g)
        orderS = sorted(s)
        sumr = 0
        indx = 0
        for i in range(len(orderG)):
            indx = findIndex(orderG[i],indx)
            if indx< len(s):
                sumr += 1
            else:
                break
            indx += 1
        return sumr
  1. (leetcode 860) 柠檬水找零
class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        if not bills:
            return True
        
        changes = {5:0,10:0}
        for v in bills:
            if v == 5:
                changes[5] += 1
            elif v == 10:
                if changes[5] == 0:
                    return False
                else:
                    changes[5] -= 1
                    changes[10] += 1
            else:
                if changes[5] == 0:
                    return False
                if changes[10] != 0:
                    changes[10] -= 1
                    changes[5] -= 1
                else:
                    if changes[5] < 3:
                        return False
                    changes[5] -= 3
        return True

leetcode 简单题

标签:element   ace   initial   add   enumerate   push   struct   利用   turn   

原文地址:https://www.cnblogs.com/curtisxiao/p/10679145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!