巧妙的收集答案


巧妙收集答案为力求一个循环出结果

题目链接

  1. 3倍子串
  2. k被区间
  3. 循环播放
  4. 子串简写
  5. 最近距离

3倍子串

代码如下

# 思想:前缀和两个数对3的余数相同则这两个数之间的和就是可以被3整除
# 0,1,2,3 前缀和-> 0,1,3,6  %3-> 0,1,0,0 
s = input()
s = [0]+list(map(int,s))
cnt = [1,0,0]
ans = 0
for i in range(1,len(s)):
    s[i] = (s[i]+s[i-1])%3
    ans += cnt[s[i]]
    cnt[s[i]] += 1
print(ans)

k被区间

# 思路,前缀和%K,有相同的值,说明他们之间是可以整除k的
# 比如:2 10 5   前缀和:2,12,17   %5:2,2,2  相同都是2说明有1+2=3个区间
n,k = map(int,input().split())
cnt = [0]*k
cnt[0]=1
ans = 0
s = 0
for _ in range(n):
  s += int(input())
  t = s%k
  ans += cnt[t]
  cnt[t] += 1
print(ans)

循环播放

from bisect import bisect_left
n = int(input())
a = [0]+list(map(int,input().split()))
for i in range(1,n+1):
    a[i] += a[i-1]
t = int(input())
rest = t%a[-1]  # 求播完多整遍之后还剩下还有多少轮
if rest == 0:   # 正好播完
    print(n)
else:
    print(bisect_left(a,rest))  # 采用二分查找

子串简写

k = int(input())
s,c1,c2 = input().split()
cnt = 0 # 看前面有多少个符合条件的c1
ans = 0 # 计算结果
for i,c in enumerate(s,1):
  if i >= k and s[i-k] == c1:
    cnt += 1
  if c == c2:
    ans += cnt
print(ans)

最近距离

n = int(input())
a = list(map(int,input().split()))
b = [i for i,v in enumerate(a) if v == 0]
m = len(b) # a中有多少个0
res = [0] * n
cnt = 0     # 计算遍历当前的第几个0
for i,v in enumerate(a):
    if v == 0:
        cnt += 1
    elif cnt == 0:
        res[i] = b[0]-i
    elif cnt == m:
        res[i] = i - b[-1]
    else:
        res[i] = min(b[cnt]-i,i-b[cnt-1])
print(*res)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

peanut666888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值