# 题目

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗？


输入: [2,2,1]



输入: [4,1,2,1,2]



# 代码

class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for num in nums:
ans ^= num
return ans


k进制版：

class Solution:
def singleNumber(self, nums: List[int]) -> int:
def decimal_to_k(num: int, k: int) -> tuple:
if num < 0:
is_negative = 1
num *= -1
else:
is_negative = 2
ans = []
while num >= k:
ans.append(num % k)
num //= k
ans.append(num)
return (is_negative, ans[::-1])

def k_to_decimal(k_nums: tuple, k: int) -> int:
is_negative, knum = k_nums[0], k_nums[1]
ans = 0
for index, digit in enumerate(knum[::-1]):
ans += (k ** index * digit)
return ans * (-1 if is_negative == 1 else 1)

def occur_once(nums: list, k: int) -> int:
prev_sign, prev = decimal_to_k(nums[0], k)
for num in nums[1:]:
cur_sign, cur_k = decimal_to_k(num, k)
# num
min_length = min(len(prev), len(cur_k))
new_prev = []
for index in range(1, min_length + 1):
new_prev.append((cur_k[-index] + prev[-index]) % k)
new_prev.reverse()
new_prev = cur_k[:(len(cur_k) - min_length)] + new_prev
new_prev = prev[:(len(prev) - min_length)] + new_prev
prev = new_prev
# sign
prev_sign = (prev_sign + cur_sign) % k
return k_to_decimal((prev_sign, prev), k)

return occur_once(nums, 2)


09-24 298
02-24 66
09-24 654
04-10 115
08-06 129
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客