Python Solution -- Simple to understand!!

  • 0
    def sortTransformedArray(self, nums, a, b, c):
        if a == 0:
            return self.linearCase(nums, a, b, c)
            return self.quadCase(nums, a, b, c)
    def linearCase(self, nums, a, b, c):
        # if line is downward sloping, then largest x values come first, otherwise, opposite
        if b < 0:
            return [self.transform(a,b,c,x) for x in list(reversed(nums))]
            return [self.transform(a,b,c,x) for x in nums]
    def quadCase(self, nums, a, b, c):
        vertex = 1.0 * -b/(2*a)
        res = []
        left, right = 0, len(nums)-1
        while len(res) != len(nums):
            if abs(vertex-nums[left]) > abs(vertex-nums[right]):
                left += 1
                right -= 1
        # if opening upwards, then we want the x values closest to vertex to come first. so reverse
        if a > 0:
            res = list(reversed(res))
        return [self.transform(a,b,c,x) for x in res]
    def transform(self, a, b, c, x):
        return a*x**2 + b*x + c

Log in to reply

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