```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 异或运算:
# 1. a ^ 0 = a
# 2. a ^ a = 0
# 3. 满足交换律和结合率
res = 0
for num in nums:
res = res ^ num # 把所有的数进行异或,两个的消成0,再和1个的异或得到1个的
return res
```
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
votes = 0
for num in nums:
# 如果票数为0,则众数在剩下的集合里,重新设置当前数为众数
if votes == 0: x = num
# 和众数相同的票数+1,和众数不同的票数-1
votes += 1 if num == x else -1
return x
```
```python
class Solution:
def sortColors(self, nums: List[int]) -> None:
n = len(nums)
if n < 2: return
def swap(nums, i, j):
nums[i], nums[j] = nums[j], nums[i]
# 以下区间结合为全区间
# all in [0, zero) = 0
# all in [zero, i) = 1
# all in [two, len - 1] = 2
# 各指针初始化为空区间
zero = 0
i = 0
two = n
while i < two: # 当 i == two 上面的三个子区间正好覆盖了全部数组
if nums[i] == 0: # [0, zero)取不到,先换再加
swap(nums, i, zero)
i += 1
zero += 1
elif nums[i] == 2:
two -= 1 # [two, len - 1]取得到,先减再换
swap(nums, i, two)
else:
i += 1
```