【剑指Offer】面试题56 - II. 数组中数字出现的次数 II

题目

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

示例 1:

输入:nums = [3,4,3,3]
输出:4

示例 2:

输入:nums = [9,1,7,9,7,9,7]
输出:1

限制:

  • 1 <= nums.length <= 10000
  • 1 <= nums[i] < 2^31

思路一:哈希

先统计每个数出现次数,然后遍历找到只出现一次的数字。

代码

时间复杂度:O(n)
空间复杂度:O(n)

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        unordered_map<int, int> ump;
        for (auto n : nums) {
            if (ump.count(n) == 0) {
                ump.insert({n, 1});
            } else {
                ++ump[n];
            }
        }
        for (auto it = ump.begin(); it != ump.end(); ++it) {
            if (it->second == 1) return it->first;
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/galaxy-hao/p/12815393.html
今日推荐