0
点赞
收藏
分享

微信扫一扫

Leetcode 136. Single Number

梦想家们 2022-01-26 阅读 63

Problem

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Algorithm

Sort the array and then scan for the only number.

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        if not nums:
            return 0
        slen = len(nums)
        nums.sort()
        cnt, val = 1, nums[0]
        for i in range(1, slen):
            if nums[i] == val:
                cnt += 1
            else:
                if cnt < 3:
                    return val
                else:
                    val = nums[i]
                    cnt = 1
        return val
举报

相关推荐

0 条评论