https://leetcode-cn.com/conte...python
https://leetcode-cn.com/conte...算法
class Solution: def countNegatives(self, grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) c = 0 for i in range(n-1, -1, -1): if grid[i][-1] >= 0: break for j in range(m-1, -1, -1): if grid[i][j] < 0: c += 1 else: break return c
https://leetcode-cn.com/conte...数组
第一可能查询的次数不少,区间也可能很大,若是每次查询都现算可能超时。可是每一个数字都不大。app
这时候就考虑不存数字自己,而是存连乘后的结果。例如输入的 a b c d。则存的是 a,a×b,a×b×c,a×b×c×d。这样。若是查询最后两个数相乘,就是倒数第一除以倒数第三就是 (a×b×c×d)/ (a×b)= c × d。这样每次查询只须要作一次除法,每次输入只须要作一次乘法。优化
用 python 的一个优点是,不用考虑整数溢出的问题。code
这里还有一个问题没有处理,就是 0。当时没考虑到,可是样例救了我,跑样例除了除零错误。排序
对于 0 的思路是,每次遇到 0 直接清空列表,由于前面是啥都没用了,只要超过 0 的位置,前面的都是 0 了。递归
而相应的查询的地方,长度超过列表长度,直接返回 0,由于面前确定是遇到 0 了。队列
再一个为了代码方便,直接列表第一个默认自带一个 1。ip
class ProductOfNumbers: def __init__(self): self.p = [1] def add(self, num: int) -> None: if num == 0: self.p = [1] else: self.p.append(self.p[-1] * num) def getProduct(self, k: int) -> int: if k >= len(self.p): return 0 return self.p[-1] // self.p[-k-1] # Your ProductOfNumbers object will be instantiated and called as such: # obj = ProductOfNumbers() # obj.add(num) # param_2 = obj.getProduct(k)
https://leetcode-cn.com/conte...
贪心算法。使用优先队列,先从最小的一天开始安排。
策略是按照开始日期分组,每一组(也就是天天)只取一个结束时间最先的(也就是会议长度最短的)。而后这把一组其余的全部其余会议的开始时间修改成下一天,放入优先队列排序。
大体是在这样,可是能够有一些小的优化,好比结束日期就是当前处理的一天的会议就能够直接安排上。由于这个会议安排上必定不会影响后面别的会。
总体的贪心策略就是尽量安排这一天开一个结束日期最先的会。
import queue class Solution: def maxEvents(self, events: List[List[int]]) -> int: q = queue.PriorityQueue() for e in events: q.put(e) e = q.get() cnt = 1 cd = e[0] + 1 while not q.empty(): e = q.get() if e[0] == cd: if e[1] >= cd: cd += 1 cnt += 1 elif e[0] > cd: cd = e[0] + 1 cnt += 1 else: # e[0] < cd if e[1] == cd: cd += 1 cnt += 1 if e[1] > cd: e[0] = cd q.put(e) return cnt
https://leetcode-cn.com/conte...
这道题目找到规律后实现很简单。
由于两个步骤是交替进行的。因此当前状态中最大的一个数就必然是 x。根据当前状态能推出上一步的状态。
而后就能够推出它被设成 x 以前的值。就是 当前的 x -(当前数组和 - 当前的 x)
而后递归调用。
class Solution: def isPossible(self, target: List[int]) -> bool: while True: cx = max(target) if cx == 1: return True idx = target.index(cx) s = sum(target) lv = cx - (s - cx) #print(lv) if lv < 1: return False target[idx] = lv #print(target)
欢迎来个人博客: https://codeplot.top/
个人博客刷题分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/