Python O(nlogV) time


  • 2

    Just calculate combinations vertically.

    class Solution(object):
        def totalHammingDistance(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ans = 0
            mask = 1
            for j in range(0, 32):
                ones = zeros = 0
                for num in nums:
                    if num & mask:
                        ones += 1
                    else:
                        zeros += 1
                ans += ones * zeros
                mask = mask << 1
            return ans
    

  • 0
    S

    nice ! but could replace:

    for i in xrange(0, len(nums)):

    with

    n = len(nums)
    for i in xrange(n)

    and

    range(0,32)

    replace by

    xrange(32)


  • 0

    Yeah, that's more elegant and pythonic but a little bit difficult to understand for those who don't use Python.


  • 2

    @sunshinely said in Python O(nlogV) time:

    n =  len(nums)
    for i in xrange(n)
    

    What's the point of introducing the variable n?

    And it really should be for num in nums.


Log in to reply
 

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