leetcode

Description:

leetcode-985

Submission:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

class :
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
ans = []
for query in queries:
val, ind = query
A[ind] += val
temp = 0
for a in A:
if (a % 2 == 0):
temp += a
ans.append(temp)
return ans

# 改进后(better,but still TLE)
class :
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
ans = []
even_id = []
temp = 0
for ind, a in enumerate(A):
if (a % 2 == 0):
even_id.append(ind)
temp += a
for query in queries:
val, ind = query
A[ind] += val
if (ind in even_id and A[ind] % 2 == 0):
temp += val
elif (ind in even_id and A[ind] % 2 != 0):
temp -= (A[ind] - val)
even_id.remove(ind)
elif (ind not in even_id and A[ind] % 2 == 0):
temp += A[ind]
even_id.append(ind)
else:
pass
ans.append(temp)
return ans

# 官方解法
class :
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
S = sum(x for x in A if x % 2 == 0) # 这里和我想法一致
ans = []

for x, k in queries:
if A[k] % 2 == 0: S -= A[k]
A[k] += x
if A[k] % 2 == 0: S += A[k] # 这里我考虑了所有情况,但其实没有必要,因此TLE
ans.append(S)

return ans

Acceptance:

ac

  仅从思路上来说,我已经很接近官方解法了,区别在于我考虑了过多的情况,且使用了even_id来保存下标,这些操作导致时间开销较大。