拆分+重排,一行搞定
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
return [*chain(*zip(sorted(nums[::2]),sorted(nums[1::2],reverse=True)),([max(nums[::2])] if len(nums)&1 else []))]
分正负,利用字符串重排
class Solution:
def smallestNumber(self, num: int) -> int:
seq,n=sorted([x for x in str(num) if x not in ('0','-')]),str(num).count('0')
return int(seq[0]+'0'*n+''.join(seq[1:])) if num>0 else -int(''.join(seq[::-1])+'0'*n)
- 要求:设计
O(1) 的flip() (因为flip最多可能调用
1
0
5
10^5
105次) - 提示:
至多调用 toString 方法 5 次 (说明toString() 可以为O(n) ) - 结论:设置标记位
flag ,只在toString() 中翻转(而在其他函数中只修改标记位)
class Bitset:
def __init__(self, size: int):
self.num=[0]*size
self.cnt=0
self.size=size
self.flag=False
def fix(self, idx: int) -> None:
if self.num[idx] ^ self.flag == 0:
self.cnt+=1
self.num[idx] = 1-self.num[idx]
def unfix(self, idx: int) -> None:
if self.num[idx] ^ self.flag == 1:
self.cnt-=1
self.num[idx] = 1- self.num[idx]
def flip(self) -> None:
self.flag = not self.flag
self.cnt = self.size - self.cnt
def all(self) -> bool:
return self.cnt==self.size
def one(self) -> bool:
return self.cnt>0
def count(self) -> int:
return self.cnt
def toString(self) -> str:
return ''.join(map(str,[i^self.flag for i in self.num]))
从排行榜看到的大神一行解法👇
class Solution:
def minimumTime(self, s):
return min(reduce(lambda r, t: (min(r[0], r[1] + n - t[0]), min(r[1] + [0, 2][t[1] == '1'], t[0] + 1)), enumerate(s), (n := len(s), 0)))
很巧妙的利用了reduce,其实等同于下面代码:
class Solution:
def minimumTime(self, s):
n=len(s)
res=(n,0)
for i,j in enumerate(s):
res=(min(res[0], res[1] + n - i), min(res[1] + [0, 2][j == '1'], i + 1))
return min(res)
reduce函数用法详解可以看我的另一篇文章:十个例子学会reduce函数
总结
T1+T2+T4,共1+2+1四行代码
|