1、位与异或
根据相同数异或为零以及零与任何数异或仍是其本身的性质,可以得到两个只出现一次数字的异或值,且两个数的二进制位中必然有一位是不相同的,因为其不能为0。
将列表中的值遍历与其中低位第一个为1的数进行与运算,可以将其分为两组。将两组分别进行异或,最后得到两个只出现一次的数字。
低位第一个为1的位数可以通过其与其反值进行与运算得到。
代码
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor = 0
for num in nums:
xor ^= num
mask = xor & (-xor)
type1=type2=0
for num in nums:
if num & mask:
type1 ^= num
else:
type2 ^= num
return [type1, type2]
2、暴力破解
直接遍历,使用另外的新列表,如果在新列表中已经存在相应的值,将其从新列表中移除;如果不存在,则添加进新列表。最后新列表中剩下的就是需要的结果。
代码
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
num1 = []
for num in nums:
if num not in num1:
num1.append(num)
else:
num1.remove(num)
return num1
链接:https://leetcode-cn.com/problems/single-number-iii/solution/260-zhi-chu-xian-yi-ci-de-shu-zi-ii-by-s-juz8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。