1. 程式人生 > 其它 >leetcode 136. Single Number(python)

leetcode 136. Single Number(python)

技術標籤:leetcodeleetcode

描述

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/