题目
- 题号:136
- 难度:简单
- https://leetcode-cn.com/problems/single-number/
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
实现
第一种:通过集合的方法
C# 语言
public class Solution
{
public int SingleNumber(int[] nums)
{
HashSet<int> h = new HashSet<int>();
for (int i = 0; i < nums.Length; i++)
{
if (h.Contains(nums[i]))
{
h.Remove(nums[i]);
}
else
{
h.Add(nums[i]);
}
}
return h.ElementAt(0);
}
}
Python 语言
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
h = set()
for num in nums:
if num in h:
h.remove(num)
else:
h.add(num)
return list(h)[0]
第二种:利用位运算的方法。
A: 00 00 11 00
B: 00 00 01 11
A^B: 00 00 10 11
B^A: 00 00 10 11
A^A: 00 00 00 00
A^0: 00 00 11 00
A^B^A: = A^A^B = B = 00 00 01 11
"异或"操作满足交换律和结合律。
C# 实现
public class Solution
{
public int SingleNumber(int[] nums)
{
int result = 0;
for (int i = 0; i < nums.Length; i++)
{
result ^= nums[i];
}
return result;
}
}
Python 实现
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for item in nums:
result ^= item
return result