Python Solution with O(n) complexity

  • 0

    The first thing we have to do is to sort the given list nums. This is achieved using this:


    After that we have to check every alternate number is equal to its right neighbor or not by incrementing loop variable i by 2.
    If we don't find the two consecutive number same then we can break our loop and print the number which is nums[i].
    If we have not encountered any number yet then our last number must be the single number and we can print that using nums[-1].
    Finally code:

    class Solution(object):
        def singleNumber(self, nums):
            :type nums: List[int]
            :rtype: int
            for i in range(0,len(nums)-1,2):
                if nums[i]!=nums[i+1]:
                    return nums[i]
            return nums[-1]

    Thank You

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.