照例,首先本人笨方法:
class Solution:
def xorOperation(self, n: int, start: int) -> int:
tmp=start
for i in range(1,n):
tmp=tmp^(start+2*i)
return tmp
此方法时间复杂度为O(n)(线性时间):每增加一个数,需要多求一次tmp。空间复杂度O(1)(常量空间):使用的额外辅助空间不随N的变化而变化。
降空间复杂度:
class Solution:
def xorOperation(self, n: int, start: int) -> int:
s=int(start/2)
def cal(s):
if s%4==0:
return s
if s%4==1:
return 1
if s%4==2:
return s+1
if s%4==3:
return 0
ans=cal(s-1)^cal(s+n-1)
if start%2==1 and n%2==1:
e=1
else:
e=0
return ans*2|e
此方法时间复杂度和空间复杂度均为O(1)。
其中,/2,*2操作可换用>>,<<。第二个if语句可简写为e=start&n&1。