T1:6245. 找出中枢整数
■第一种方法简单粗暴,直接等差数列x左边和等于x右边和
class Solution:
def pivotInteger(self, n: int) -> int:
for x in range(n+1):
k1 = (1+x)*x
k2 = (n +x)*(n-x+1)
if k1 == k2:
return x
else:
return -1
■第二种方法,由于题目只有x和n两个变量。所有直接可以用n表示出x:x=(n(n+1)/2)**0.5,判断x是否为整数即可。
class Solution:
def pivotInteger(self, n: int) -> int:
m = n * (n+1) //2
x = int(m ** 0.5)
if x * x == m:
return x
return -1
T2: 6246. 追加字符以获得子序列
■我最开始是这样写的,结果部分用例无法通过,后来发现在第五行中for循环重复取了s前面已经认为相同的数。
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
ls = ''
for t1 in t:
for s1 in s:
if s1 ==t1:
ls = ls + s1
break
else:
break
return len(t) -len(ls)
■修改一下
#第一种
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
num = 0
for i in range(len(s)):
if num == len(t):
return 0
if s[i] == t[num]:
num+=1
return len(t) -num
#第二种
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
i, n = 0, len(s)
for j, c in enumerate(t):
while i< n and s[i] != c:
i+=1
if i == n:
return len(t) - j
i +=1
return 0
T3: 6247. 从链表中移除节点
■实话这种方法没弄太懂,学一学up灵茶
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None: return head # 输入保证链表不为空
node = self.removeNodes(head.next) # 返回的链表头一定是最大的
if node.val > head.val: return node # 删除 head
head.next = node # 不删除 head
return head
T1: 4722. 数列元素
n = int(input())
i = 0
while i < 500:
i += 1
if n == (i + 1) * i / 2:
print('YES')
break
else:
print('NO')
T2: 4723. 队列
n = int(input())
i = 0
ls1 = ['a','b','c','d','e']
while 1:
i+=1
k1 = -5*(1-2**(i-1))
k2 = -5*(1-2**i)
if n> k1 and n<= k2:
if (n-k1)%(2**(i-1)) !=0:
print(ls1[int((n-k1)//(2**(i-1)))])
break
else:
print(ls1[int((n-k1)//(2**(i-1))-1)])
break