LeetCode——136. 只出现一次的数字

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

说明:

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

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number

哈希表

这道题给了我们一个非空的整数数组,说是除了一个数字之外所有的数字都正好出现了两次,让我们找出这个只出现一次的数字。题目中让我们在线性的时间复杂度内求解,那么一个非常直接的思路就是使用 HashSet,利用其常数级的查找速度。遍历数组中的每个数字,若当前数字已经在 HashSet 中了,则将 HashSet 中的该数字移除,否则就加入 HashSet。这相当于两两抵消了,最终凡事出现两次的数字都被移除了 HashSet,唯一剩下的那个就是单独数字了,参见代码如下:

C++

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        unordered_set<int> st;
        for (int num : nums) {
            if (st.count(num)) st.erase(num);
            else st.insert(num);
        }
        return *st.begin();
    }
};

Java

class Solution {
    public int singleNumber(int[] nums) {
        Set<Integer> st = new HashSet<>();
        for (int num : nums) {
            if (!st.add(num)) st.remove(num);
        }
        return st.iterator().next();
    }
}

python

class Solution(object):
    def singleNumber(self, nums):
        hash_table = {}
        for i in nums:
            try:
                hash_table.pop(i)
            except:
                hash_table[i] = 1
        return hash_table.popitem()[0]

二进制

题目中让我们不使用额外空间来做,本来是一道非常简单的题,但是由于加上了时间复杂度必须是 O(n),并且空间复杂度为 O(1),使得不能用排序方法,也不能使用 HashSet 数据结构。那么只能另辟蹊径,需要用位操作 Bit Operation 来解此题。逻辑异或的真值表为:

A B
F F F
F T T
T F T
T T F

由于数字在计算机是以二进制存储的,每位上都是0或1,如果我们把两个相同的数字异或,0与0 '异或' 是0,1与1 '异或' 也是0,那么我们会得到0。根据这个特点,我们把数组中所有的数字都 '异或' 起来,则每对相同的数字都会得0,然后最后剩下来的数字就是那个只有1次的数字。

C++

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

Java

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int num : nums) res ^= num; 
        return res;
    }
}

python

class Solution(object):
    def singleNumber(self, nums):
        a = 0
        for i in nums:
            a ^= i
        return a
原文地址:https://www.cnblogs.com/wwj99/p/12382023.html