leetcode 136. Single Number(python)

描述

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:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

解析

根据题意,找出只出现过一次的元素,只要在遍历的时候使用异或的运算,即可得到答案。

解答

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/

你可能感兴趣的:(leetcode,leetcode)