LeetCode------------只出现一次的数字

 

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

说明:

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

方法 1:哈希表
算法

我们用哈希表避免每次查找元素是否存在需要的 O(n)O(n) 时间。

遍历 \text{nums}nums 中的每一个元素
查找 hash\_tablehash_table 中是否有当前元素的键
如果没有,将当前元素作为键插入 hash\_tablehash_table
最后, hash\_tablehash_table 中仅有一个元素,用 popitem 获得它

python

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        hash_table = {}
        for i in nums:
            try:
                hash_table.pop(i)
            except:
                hash_table[i] = 1
        return hash_table.popitem()[0]
class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer i : nums) {
            Integer count = map.get(i);
            count = count == null ? 1 : ++count;
            map.put(i, count);
        }
        for (Integer i : map.keySet()) {
            Integer count = map.get(i);
            if (count == 1) {
                return i;
            }
        }
        return -1; // can't find it.
    }
}

作者:yinyinnie
链接:https://leetcode-cn.com/problems/two-sum/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
来源:力扣(LeetCode)

方法 2:位操作
概念

如果我们对 0 和二进制位做 XOR 运算,得到的仍然是这个二进制位
a \oplus 0 = aa⊕0=a
如果我们对相同的二进制位做 XOR 运算,返回的结果是 0
a \oplus a = 0a⊕a=0
XOR 满足交换律和结合律
a \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = ba⊕b⊕a=(a⊕a)⊕b=0⊕b=b
所以我们只需要将所有的数进行 XOR 操作,得到那个唯一的数字。

python

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = 0
        for i in nums:
            a ^= i
        return a

java

int ans = nums[0];
if (nums.length > 1) {
   for (int i = 1; i < nums.length; i++) {
      ans = ans ^ nums[i];
   }
 }
 return ans;

作者:yinyinnie
链接:https://leetcode-cn.com/problems/two-sum/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
来源:力扣(LeetCode)

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/zhi-chu-xian-yi-ci-de-shu-zi-by-leetcode/
来源:力扣(LeetCode)
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值