Python in O(n)?


  • 0
    A

    I did something like this, but it was considerably slower than the solution involving sort, about 4 times slower.

    class Solution(object):
        def arrayPairSum(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            s = 0
            d = {}
            for k in nums:
                d[k + 10000] = d.get(k + 10000, 0) + 1
            f = 1
            for k in range(20001):
                v = d.get(k, 0)
                if v:
                    q, r = divmod(v, 2)
                    s += (k - 10000)*q + r*f*(k - 10000)
                    if r:
                        f = (f + 1)%2
            return s
    

    What is happening


Log in to reply
 

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