【LeetCode 136】只出现一次的数字

136. Single Number

题目难度: 简单

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

解题思路

利用set来解题,如果set中不存在就加进去,存在就移除。这样最后剩下的一定是那个只出现了一次的元素

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
   def singleNumber(self, nums):
       """
      :type nums: List[int]
      :rtype: int
      """
       nums_set = set()
       for i in range(len(nums)):
           if nums[i] in nums_set:
               nums_set.remove(nums[i])
           else:
               nums_set.add(nums[i])

       return nums_set.pop()
黄小豆 wechat
关注我的公众号,同步推送博客内容
坚持原创技术分享,您的支持将鼓励我继续创作!
0%