9

Leetcode-136-只出现一次的数字

 2 years ago
source link: https://zhangslob.github.io/2020/02/23/Leetcode-136-%E5%8F%AA%E5%87%BA%E7%8E%B0%E4%B8%80%E6%AC%A1%E7%9A%84%E6%95%B0%E5%AD%97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Leetcode-136-只出现一次的数字

发表于 2020-02-23

| 分类于 leetcode

这是崔斯特的第一百一十四篇原创文章

努力、奋斗

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

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

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

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

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

使用map保存每个元素在数组中出现的次数,key是元素,value是出现次数。

这种方法显然不符合题目需求,不使用额外空间。

按位异或:参与运算的两个值,如果两个相应bit位相同,则结果为0,否则为1。

0^0 = 0,
1^0 = 1,
0^1 = 1,
1^1 = 0

异或运算的符号是^,其定义如下:

a xor b = (a & ^b) | (^a & b)
a b a xor b
0 0 0
0 1 1
1 0 1
1 1 0

因为有定律a ^ b ^ a = b,所以我们这里就可以使用异或来做。

def single_number(numbers):
tmp = 0
for n in numbers:
tmp ^= n
return tmp
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
return result;

可以看到非常简单。

这些全都是计算机基础知识,但是自己不知道,只能说明自己基础差,以后补得起来吗。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK