Leetcode 136. Single Number

阅读 63

2022-01-26

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)

0 0 举报