O(1) memory result

  • 0

    I have saw many result with the usage if x+y and y+x, this cmp process need to load extra memory. my solution will request no extra memory in the compare process

    class Solution:
      # @param {integer[]} nums
      # @return {string}
      def numCmp(self,x,y):
        xc, yc, xs, ys = 0, 0, len(x), len(y)
        while True:
          if ord(x[xc%xs]) == ord(y[yc%ys]):
            xc += 1
            yc += 1
            if xc>len(x) and yc>len(y):
              return 0
            return ord(x[xc%xs]) - ord(y[yc%ys])
      def largestNumber(self, nums):
        nums = [str(i) for i in nums]
        nums.sort(cmp=self.numCmp, reverse=True)
        return ''.join(nums).lstrip('0') or '0'

Log in to reply

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