LeetCode: 137. Single Number II
题目描述
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3  Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99  解题思路
哈希表(时间复杂度:O(n), 空间复杂度:O(n))
将每个数装入哈希表中,统计出现个数。
位运算(时间复杂度: O(n), 空间复杂度:O(1))
统计各位中 1 的个数,其模 3 的结果就是单独那个数的该位的值
AC 代码
哈希表
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        unordered_map<int, int> numsCount;
        // 统计
        for(int num : nums)
        {
            ++numsCount[num];
        }
        // 判断
        for(auto iter = numsCount.begin(); iter != numsCount.end(); ++iter)
        {
            if(iter->second == 1) return iter->first;
        }
        return -1;
    }
};  位运算
class Solution
{
public:
    int singleNumber(vector<int>& nums) 
    {
        int ans = 0;
        for(int i = 0; i < 32; ++i)
        {
            int bitSum = 0;
            // 统计各位中 1 的个数,其模 3 的结果就是单独那个数的该位的值
            for(int num : nums)
            {
                bitSum += ((num >> i) & 1);
            }
            ans += ((bitSum % 3) << i);
        }
        return ans;
    }
};
京公网安备 11010502036488号