Python beginner friendly solution. fully commented


  • 0
    K
    
    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            # variable to hold the single number
            single_num = None
    
            # if length is 1, return number
            if len(nums) == 1:
                single_num = nums[0]
                
            else:
                # sort the list
                nums.sort()
                
                
                # check boundary cases
                if nums[0] != nums[1]:
                    single_num = nums[0]
                elif nums[-1] != nums[-2]:
                    single_num = nums[-1]
                else:
                    # variables initialized for looping
                    MAX_LENGTH = len(nums) - 1
                    i = 1
                    not_found = True
                    
                    while i < MAX_LENGTH and not_found:
                        # check the previous and next number
                        curr_num = nums[i]
                        next_num = nums[i+1]
                        prev_num = nums[i-1]
                        # if adjacent numbers differ, we landed on the single number
                        if curr_num != next_num and curr_num != prev_num:
                            # track single number and leave loop
                            not_found = False
                            single_num = curr_num
                        i += 1
            
            # return the single number
            return single_num
    
    

  • 0
    K

    Sorting the list takes it from linear O(N) to linearithmic time O(nlgn).


Log in to reply
 

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