Python solution without using abs()


  • 6
    P

    Basically the same idea a lot of previous solutions implement. I was thinking whether we could get rid of the abs operation around the index to make the code faster. I exploited the fact that each repeating elements don't appear more than twice so I set the increment to 0.4 as to maintain the value of the index when being floored.

    The funny thing is the code actually ran slower LOL. However just want to share with you guys my idea.

    class Solution(object):
        def findDisappearedNumbers(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            for v in nums:
                index = int(v) - 1
                nums[index] += 0.4
            return [i+1 for i in xrange(len(nums)) if nums[i] == int(nums[i])]
    

Log in to reply
 

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