描述
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:
1 | Input: nums = [2,2,3,2] |
Example 2:
1 | Input: nums = [0,1,0,1,0,1,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.
分析
很有意思的一道题,与上一道题leetcode-137-Single-Number不同的是,这里的元素是三个为一组。可以用位运算,将所有的数字看作二进制的数,把所有的数字在每一位出现的次数加起来,如果是3的倍数,那么要找的那个数在该位上就是0,否则是1
解决方案1(Python)
1 | class Solution: |
解决方案2(C++)
1 | class Solution { |