给定一个数组,寻求数组中只出现一次的数字(力扣136)

  1. 只出现一次的数字
    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

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

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

- 哈希

最近正学哈希数据结构,第一反应就是采用哈希表计数,遍历一遍数组之后再对哈希进行遍历,寻找出现次数为1的元素,时间复杂度O(N),空间复杂度O (N)

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
     unordered_map<int, int> hash;//key值为元素值,val放出现次数
        int len = nums.size();
        for (int i = 0; i < len; i++) {
    
    
            unordered_map<int, int>::iterator it = hash.find(nums[i]);
            if (it == hash.end())//哈希表中无该数
                hash[nums[i]] = 1;//将该数的val置1
            else {
    
    
                hash[nums[i]]++; //若已经存在,val加一
            }
        }
        for (auto val : hash) {
    
    //将hash表中所有数据进行遍历,寻找出现次数为1的元素
            if (val.second == 1)
                return val.first;
        }
        return 0;
    }
};

- 位运算
看题解之后才想起来还有个这个精妙的运算:异或,相同为假不同为真,具体运算如下:

交换律:a ^ b ^ c <=> a ^ c ^ b

任何数于0异或为任何数 0 ^ n => n

相同的数异或为0: n ^ n => 0
举个例子:
在这里插入图片描述

var a = [2,3,2,4,4]
2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
     int ans=0;
     for(auto num:nums)
        ans^=num;
        
        return ans;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Genius_bin/article/details/113103176