给出题目一的试题链接如下:
这一题只要不断地将重复地删除anagram的结果就行了。
给出python代码实现如下:
class Solution:
def removeAnagrams(self, words: List[str]) -> List[str]:
def is_anagram(word1, word2):
cnt1 = Counter(word1)
cnt2 = Counter(word2)
return len(cnt1) == len(cnt2) and all(cnt1[ch] == cnt2[ch] for ch in cnt1)
res = [words[0]]
for w in words[1:]:
if not is_anagram(res[-1], w):
res.append(w)
return res
提交代码评测得到:耗时140ms,占用内存13.9MB。
给出题目二的试题链接如下:
这一题同样比较简单,我们只需要将特殊的楼层进行一下排序,然后取其间隔的最大值即可。
给出python代码实现如下:
class Solution:
def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:
special = [bottom-1] + sorted(special) + [top+1]
n = len(special)
return max(special[i+1]- special[i]-1 for i in range(n-1))
提交代码评测得到:耗时1042ms,占用内存28.6MB。
给出题目三的试题链接如下:
这一题我们只需要统计每一个比特位上面出现过的所有的数字的次数即可。这些数的比特与结果一定不为0,但是超过这个数,那么一定为0。
给出python代码实现如下:
class Solution:
def largestCombination(self, candidates: List[int]) -> int:
cnt = [0 for _ in range(24)]
for x in candidates:
idx = 0
while x != 0:
cnt[idx] += x % 2
x = x // 2
idx += 1
return max(cnt)
提交代码评测得到:耗时2083ms,占用内存24.9MB。
给出题目四的试题链接如下:
这一题就是一个区间合并的问题,讲道理也算是一个老题了,就不在这里过多展开了,仅给出code如下。
给出python代码实现如下:
class CountIntervals:
def __init__(self):
self.intervals = []
self.cnt = 0
def add(self, left: int, right: int) -> None:
if self.intervals == []:
self.intervals.append([left, right])
self.cnt = right-left+1
return
l = bisect.bisect_left(self.intervals, [left, left])
if l > 0 and self.intervals[l-1][1] >= left:
l -= 1
left = min(left, self.intervals[l][0])
r = bisect.bisect_right(self.intervals, [right, math.inf])
if r > 0 and self.intervals[r-1][1] > right:
right = self.intervals[r-1][1]
self.cnt += right - left + 1
for i in range(l, r):
self.cnt -= self.intervals[l][1] - self.intervals[l][0] + 1
self.intervals.pop(l)
self.intervals.insert(l, [left, right])
return
def count(self) -> int:
return self.cnt
提交代码评测得到:耗时1362ms,占用内存54.7MB。