lc136

188 阅读1分钟

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:

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

思路:

1. 建个字典d,遍历一遍nums,nums值作为键添加进字典d,出现一次,d['num']++,
完成后遍历字典d,找出value为1的,返回键,ojbk
2. 位运算,异或操作

python3 思路1解法

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        d = {}
        for i in nums:
            if str(i) in d.keys():
                d[str(i)] += 1
            else:
                d[str(i)] = 1

        for key, value in d.items():
            if value ==1:
                return int(key)

思路2解法

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a=0
        for n in nums:
            a ^=n
        return a