[LeetCode] Challenge log 136

136. Single Number
  1. Use hash table to mark element that shows before.
  2. Use math, 2 * sum of all unique number - sum of all.
  3. Use a XOR 0 = a, a XOR a =0.

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

1
2
Input: [2,2,1]
Output: 1

Example 2:

1
2
Input: [4,1,2,1,2]
Output: 4

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# s1
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
uni = set()
while len(nums) > 0:
num = nums.pop()
if num in uni:
uni.remove(num)
else:
uni.add(num)
return uni.pop()
1
2
3
4
5
6
7
8
# s2
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2 * sum(set(nums)) - sum(nums)
1
2
3
4
5
6
7
8
9
10
# s3
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(1, len(nums)):
nums[0] = nums[0] ^ nums[i]
return nums[0]
0%