Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Note:
根据题意,找出只出现过一次的元素,只要在遍历的时候使用异或的运算,即可得到答案。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in nums:
res ^= i
return res
Runtime: 100 ms, faster than 91.81% of Python online submissions for Single Number.
Memory Usage: 15.6 MB, less than 84.99% of Python online submissions for Single Number.
根据题意,找出只出现过一次的元素,去重之后,根据数学公式计算就可以了。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2*sum(set(nums))-sum(nums)
Runtime: 108 ms, faster than 69.66% of Python online submissions for Single Number.
Memory Usage: 16.3 MB, less than 26.61% of Python online submissions for Single Number.
原题链接:https://leetcode.com/problems/single-number/