Python O(n) Solution


  • 0
    C
    class Solution(object):
        def singleNumber(self, nums):
            nums.sort()
            ct=0
            i=0
            a=[0,0]
            while i <len(nums):
                if i==len(nums)-2:
                    return nums[len(nums)-2],nums[len(nums)-1]
                elif i==len(nums)-1:
                    return a[0],nums[len(nums)-1]
                elif nums[i]==nums[i+1]:
                    i+=2
                else:
                    a[ct]=nums[i]
                    ct+=1
                    if ct==2:
                        return a
                    else:
                        i+=1
    

  • 0
    R

    nums.sort() already costs O(nlogn)


  • 0
    L

    What if the number exists for 3 times?
    For example
    [1,1,1,2,2,2]
    when i == 0, nums[0] == nums[1], i+=2
    now i == 2, nums[2] != nums[3], a[ct]= nums[2]
    Finally return a == [1,2]
    This is not correct.


  • 0
    C

    @rw1993 Yes you are right!


  • 0
    C

    @LeoEatle The problem says the numbers will show up exactly twice, so your case is not suitable in this situation. :]


Log in to reply
 

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