lc marathon 7.19

文章目录

        • [14. 最长公共前缀](https://leetcode.cn/problems/longest-common-prefix/)
        • [367. 有效的完全平方数](https://leetcode.cn/problems/valid-perfect-square/)
        • [232. 用栈实现队列](https://leetcode.cn/problems/implement-queue-using-stacks/)
        • [342. 4的幂](https://leetcode.cn/problems/power-of-four/)

14. 最长公共前缀

利用zip函数,将每个str都当成一个迭代

for i in zip(*strs) ==(a1[0],a2[0]…)

def longestCommonPrefix(strs) -> str:
    ls=zip(*strs)
    t=""
    for i in ls:
        if len(set(i))!=1:
            break
        else:
            t=t+i[0]
    return t

367. 有效的完全平方数

i 不能到最后一个数,否则会超时

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        if num==1:
            return True
        return isit(num)

@cache
def isit(num):
    i=1
    while(i*i<=num):
        if i*i==num:
            return True
        i+=1
    return False

232. 用栈实现队列

两个重要准则:

  1. stack2 空了才能放

  2. stack1 要放就放完

class MyQueue:


    # stack2 空了才能放
    # stack1 要放就放完
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
      

    def push(self, x: int) -> None:
        self.stack1.append(x)
        if len(self.stack2)==0:
            while(len(self.stack1)!=0):
                self.stack2.append(self.stack1.pop())
        
            
    def pop(self) -> int:
        t=self.stack2.pop()
        if len(self.stack2)==0:
            while(len(self.stack1)!=0):
                self.stack2.append(self.stack1.pop())
        return t

    def peek(self) -> int:
        if len(self.stack2)==0:
            while(len(self.stack1)!=0):
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]


    def empty(self) -> bool:
        if len(self.stack1)==0 and len(self.stack2)==0:
            return True
        else:
            return False


# 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()

342. 4的幂

i不能递增到n,否则会超时

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        if n==1:
            return True
        return num(n)
def num(n):
    i=1
    while(pow(4,i)<=n):
        if pow(4,i)==n:
            return True
        i+=1
    return False

你可能感兴趣的:(leetcode马拉松,leetcode,算法,职场和发展)