leetcode 540. Single Element in a Sorted Array (python)

219 阅读1分钟

描述

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Follow up: Your solution should run in O(log n) time and O(1) space.

Example 1:

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2	

Example 2:

Input: nums = [3,3,7,7,10,11,11]
Output: 10

Note:

1 <= nums.length <= 10^5
0 <= nums[i] <= 10^5

解析

根据题意要找出只出现过一次的元素,使用数学公式可以巧妙求解,直接求出 nums 中不重复元素的总和,然后乘 2 ,减去 nums 的所有元素的总和,即可得到答案。

解答

class Solution(object):
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(list(set(nums)))*2 - sum(nums)
                	      
		

运行结果

Runtime: 48 ms, faster than 92.07% of Python online submissions for Single Element in a Sorted Array.
Memory Usage: 16.1 MB, less than 5.77% of Python online submissions for Single Element in a Sorted Array.

原题链接:leetcode.com/problems/si…

您的支持是我最大的动力