5989. 元素计数
这是我写的:
执行用时: 36 ms,内存消耗: 15.2 MB
思路:直接排序,然后去掉左右两个数即可。
class Solution:
def countElements(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if n <= 2:
return 0
left, right = 0, n-1
while left < right:
if nums[left] == nums[left+1]:
left += 1
else:
break
left += 1
while left < right:
if nums[right] == nums[right-1]:
right -= 1
else:
break
right -= 1
return max(right - left + 1, 0)
大佬两行代码:
执行用时: 36 ms,内存消耗: 15.1 MB
思路:先找出最值,然后判断在二者之间的数量即可。
class Solution:
def countElements(self, nums: List[int]) -> int:
lo, hi = min(nums), max(nums)
return sum(lo < x < hi for x in nums)
5991. 按符号重排数组
我写的:
执行用时: 164 ms,内存消耗: 35.2 MB
思路:先分成两个数组,之后依次合并即可。
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
n = len(nums)
arr1, arr2 = [], []
for num in nums:
if num > 0:
arr1.append(num)
else:
arr2.append(num)
res = []
for i in range(n // 2):
res.append(arr1[i])
res.append(arr2[i])
return res
5990. 找出数组中的所有孤独数字
咱写的:
执行用时: 264 ms,内存消耗: 41.1 MB
思路:哈希表+集合,遍历一遍nums后再遍历哈希表即可。
class Solution:
def findLonely(self, nums: List[int]) -> List[int]:
se = set(nums)
has = {}
for num in nums:
if num not in has.keys():
has[num] = 1
else:
has[num] += 1
res = []
for k, v in has.items():
if v != 1:
continue
else:
if (k-1) not in se and (k+1) not in se:
res.append(k)
return res
大佬两行代码:
执行用时: 196 ms,内存消耗: 35.3 MB
思路:用counter会快一些。
class Solution:
def findLonely(self, nums: List[int]) -> List[int]:
c = Counter(nums)
return [x for x, v in c.items() if v == 1 and x - 1 not in c and x + 1 not in c]
5992. 基于陈述统计最多好人数
大佬写的:执行用时: 1776 ms,内存消耗: 15.2 MB
思路:二进制枚举,题解二进制枚举
class Solution:
def maximumGood(self, statements: List[List[int]]) -> int:
def check(i: int) -> int:
cnt = 0 # i 中好人个数
for j, row in enumerate(statements): # 枚举 i 中的好人 j
if (i >> j) & 1:
if any(st < 2 and st != (i >> k) & 1 for k, st in enumerate(row)):
return 0 # 好人 j 的某个陈述 st 与实际情况矛盾
cnt += 1
return cnt
return max(check(i) for i in range(1, 1 << len(statements)))