137. Single Number II
Medium
2636405Add to ListShare
Given an integer array nums
where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
- Each element in
nums
appears exactly three times except for one element which appears once.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
assert Solution().singleNumber([-2, -2, 1, 1, 4, 1, 4, 4, -4, -2]) == -4
assert Solution().singleNumber([2, 2, 3, 2]) == 3
assert Solution().singleNumber([0, 1, 0, 1, 0, 1, 99]) == 99
解题思路1:同【136 Single Number】解法,用个map存
时间复杂度:O(n),空间复杂度:O(n)
解题思路2:用个32位数组count[32],记录各位出现的次数,找出所有出现1次的位组成就是结果
补码 = 原码除符号位按位取反,末位+1
注意处理负数,因为负数在计算机里是以补码的形式保存,-1的补码是11111111111...,不断右移还是-1
时间复杂度:O(n),空间复杂度:O(1)
"""
if len(nums) == 1:
return nums[0]
count = [0] * 32
sign = 0
for num in nums:
sign += 1 if num >= 0 else 0
positive = abs(num)
for i in range(0, 32):
count[i] += (positive >> i) & 1
count[i] %= 3
result = 0
for i in range(0, 32):
result += (count[i] << i)
return result if (sign % 3 != 0) else -result