LeetCode笔记:Weekly Contest 303
Posted Espresso Macchiato
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode笔记:Weekly Contest 303相关的知识,希望对你有一定的参考价值。
1. 题目一
给出题目一的试题链接如下:
1. 解题思路
这一题思路倒是也简单,只要找到第一个重复的数字即可。
2. 代码实现
给出python代码实现如下:
class Solution:
def repeatedCharacter(self, s: str) -> str:
cnt = defaultdict(int)
for ch in s:
cnt[ch] += 1
if cnt[ch] > 1:
return ch
提交代码评测得到:耗时37ms,占用内存13.8MB。
2. 题目二
给出题目二的试题链接如下:
1. 解题思路
这一题我的思路非常的暴力,就是把每一行和每一列的元素全部记录下来,然后比较一下求个积即可。
2. 代码实现
给出python代码实现如下:
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
n = len(grid)
rows = defaultdict(int)
cols = defaultdict(int)
for i in range(n):
rows[tuple(grid[i])] += 1
cols[tuple([x[i] for x in grid])] += 1
res = 0
for row in rows:
res += rows[row] * cols[row]
return res
提交代码评测得到:耗时809ms,占用内存18.9MB。
3. 题目三
给出题目三的试题链接如下:
1. 解题思路
这一题首先就是我们先存储下每一个食物的分类和评分,然后对于每一个分类,都维护一个按照rating进行排列的数组。
然后,我们每次修改评分之后只需要同步地修改两个数组即可。
2. 代码实现
给出python代码实现如下:
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
self.foods =
self.cuisines = defaultdict(list)
for f, c, r in zip(foods, cuisines, ratings):
self.foods[f] = (r, c)
bisect.insort(self.cuisines[c], (-r, f))
def changeRating(self, food: str, newRating: int) -> None:
oldRating, cuisine = self.foods[food]
self.foods[food] = (newRating, cuisine)
idx = bisect.bisect_left(self.cuisines[cuisine], (-oldRating, food))
self.cuisines[cuisine].pop(idx)
bisect.insort(self.cuisines[cuisine], (-newRating, food))
return
def highestRated(self, cuisine: str) -> str:
return self.cuisines[cuisine][0][1]
提交代码评测得到:耗时1245ms,占用内存44MB。
4. 题目四
给出题目四的试题链接如下:
1. 解题思路
这一题同样是一个巧题,问题的关键就在于说a&b
与a|b
的各个位数当中的1的个数之和恰好就是a
和b
当中的1的位数之和。
因此,这道题就变得比较简单了。
2. 代码实现
给出python代码实现如下:
class Solution:
def countExcellentPairs(self, nums: List[int], k: int) -> int:
nums = list(set(nums))
cnt = [0 for _ in range(32)]
for x in nums:
d = 0
while x != 0:
d += x % 2
x = x // 2
cnt[d] += 1
res = 0
for i in range(32):
for j in range(32):
if i + j >= k:
res += cnt[i] * cnt[j]
return res
提交代码评测得到:耗时2884ms,占用内存32.1MB。
以上是关于LeetCode笔记:Weekly Contest 303的主要内容,如果未能解决你的问题,请参考以下文章