LeetCode 每日一题 2022/7/11-2022/7/17

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




7/11 676. 实现一个魔法字典

将单词按照长度分组
在相同长度的单词中寻找是否满足

class MagicDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        from collections import defaultdict
        self.dic=defaultdict(list)
        

    def buildDict(self, dict):
        """
        Build a dictionary through a list of words
        :type dict: List[str]
        :rtype: None
        """
        for w in dict:
            num = len(w)
            self.dic[num].append(w)
            
        

    def search(self, word):
        """
        Returns if there is any word in the trie that equals to the given word after modifying exactly one character
        :type word: str
        :rtype: bool
        """
        num = len(word)
        if num not in self.dic.keys():
            return False
        
        for w in self.dic[num]:
            tag = 0
            for i in range(num):
                if w[i]!=word[i]:
                    tag+=1
            if tag==1:
                return True
        return False



7/12 1252. 奇数值单元格的数目

用两个数组分别记录行、列被添加的次数
最后遍历每个格子在行+列的总次数是否奇数个

def oddCells(m, n, indices):
    """
    :type m: int
    :type n: int
    :type indices: List[List[int]]
    :rtype: int
    """
    row,col = [0]*m,[0]*n
    for i,j in indices:
        row[i]+=1
        col[j]+=1
    ans = 0
    for i in range(m):
        for j in range(n):
            if (row[i]+col[j])%2==1:
                ans +=1
    return ans



7/13 735. 行星碰撞

从头开始考虑
ans存放当前已处理行星
如果ans[-1]为负方向 则当前这个可以直接放入
否则 如果当前为正也可以放入
如果当前为负 则从尾开始比较


def asteroidCollision(asteroids):
    """
    :type asteroids: List[int]
    :rtype: List[int]
    """
    ans = [asteroids[0]]
    for v in asteroids[1:]:
        if ans[-1]<0 or v>0:
            ans.append(v)
            continue
        tag = True
        while ans[-1]>0:
            if ans[-1]>-v:
                tag = False
                break
            elif ans[-1]==-v:
                tag = False
                ans.pop(-1)
                break
            else:
                ans.pop(-1)
        if tag:
            ans.append(v)
    return ans


7/14 745. 前缀和后缀搜索

两个字典树 分别匹配


class WordFilter(object):

    def __init__(self, words):
        """
        :type words: List[str]
        """
        pre,suf = {},{}
        m={}
        for i,word in enumerate(words):
            m[word] = i
            
        for word in m:
            i=m[word]
            tmp = pre
            for c in word:
                if c in tmp:
                    tmp = tmp[c]
                    tmp["ind"].add(i)
                else:
                    tmp[c]={}
                    tmp = tmp[c]
                    tmp["ind"] = set([i])
            tmp = suf
            for c in word[::-1]:
                if c in tmp:
                    tmp = tmp[c]
                    tmp["ind"].add(i)
                else:
                    tmp[c]={}
                    tmp = tmp[c]
                    tmp["ind"] = set([i])
        self.pre = pre
        self.suf = suf
        self.mem={}


    def f(self, pref, suff):
        """
        :type pref: str
        :type suff: str
        :rtype: int
        """
        memtag = pref+","+suff
        if memtag in self.mem:
            return self.mem[memtag]
        tmp = self.pre
        tag = True
        for c in pref:
            if c in tmp:
                tmp = tmp[c]
            else:
                tag = False
                break
        if not tag:
            self.mem[memtag] = -1
            return -1

        prenum  = tmp["ind"]
        
        tmp = self.suf
        tag = True
        for c in suff[::-1]:
            if c in tmp:
                tmp = tmp[c]
            else:
                tag = False
                break
        if not tag:
            self.mem[memtag] = -1
            return -1
        sufnum  = tmp["ind"]
        
        l = list(prenum&sufnum)
        ans = -1
        if l:
            ans = max(l)
        self.mem[memtag] = ans
        return ans


7/15 558. 四叉树交集

dfs
如果两个节点有一个为叶子节点
如果叶子节点为true 则结果为这个叶子节点 否则为另一个叶子节点
如果两个节点均不为叶子节点
分别考虑四个子部分 如果四个部分相同 则合并
否则不合并

class Node(object):
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight

def intersect(quadTree1, quadTree2):
    """
    :type quadTree1: Node
    :type quadTree2: Node
    :rtype: Node
    """
    def check(node1,node2):
        if node1.isLeaf:
            if node1.val:
                return node1
            else:
                return node2
        if node2.isLeaf:
            if node2.val:
                return node2
            else:
                return node1
        p1 = check(node1.topLeft,node2.topLeft)
        p2 = check(node1.topRight,node2.topRight)
        p3 = check(node1.bottomLeft,node2.bottomLeft)
        p4 = check(node1.bottomRight,node2.bottomRight)
        if p1.isLeaf and p2.isLeaf and p3.isLeaf and p4.isLeaf and p1.val==p2.val==p3.val==p4.val:
            return Node(p1.val,True)
        return Node(False,False,p1,p2,p3,p4)
    return check(quadTree1, quadTree2)



7/16 剑指 Offer II 041. 滑动窗口的平均值

模拟滑动窗口 记录总和

class MovingAverage(object):

    def __init__(self, size):
        """
        Initialize your data structure here.
        :type size: int
        """
        self.l = []
        self.n = size
        self.sum = 0


    def next(self, val):
        """
        :type val: int
        :rtype: float
        """
        self.l.append(val)
        self.sum += val
        if len(self.l)>self.n:
            v = self.l.pop(0)
            self.sum -= v
        return self.sum*1.0/len(self.l)



7/17 565. 数组嵌套

不含重复元素 必定是若干个环
从头遍历 记录已经出现过的位置

def arrayNesting(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    mem = {}
    n = len(nums)
    ans = 0
    for i in range(n):
        cur = 0
        while i not in mem:
            mem[i]=1
            i = nums[i]
            cur+=1
        ans = max(ans,cur)
    return ans



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值