C++Leetcode136:只出现一次的数字

题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:
输入: [2,2,1]
输出: 1

示例 2:
输入: [4,1,2,1,2]
输出: 4

思路
1、哈希表。将数组存入哈希表中,如果重复出现,就从哈希表中删除,最后哈希表中就剩下只出现过一次的数字。注:在VS2017上测试通过,但是提交时,结果不一致,还未找到原因~

实现方法
1、哈希表

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        unordered_set<int> hashset;
        for(int key:nums){
            if(hashset.count(key)>0)
                hashset.erase(key);
            hashset.insert(key);
        }
        unordered_set<int>::iterator it=hashset.begin();
        return *it;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43434305/article/details/87889035