Just another way in Python


  • 0
    D
    class Solution(object):
        def sortTransformedArray(self, nums, a, b, c):
            """
            :type nums: List[int]
            :type a: int
            :type b: int
            :type c: int
            :rtype: List[int]
            """
            self.a = a
            self.b = b
            self.c = c
            
            n = len(nums) - 1
            start = 0
            end = n
            index = 0 if a < 0 else n
            step = 1 if a < 0 else -1
            
            res = [0] * (n+1)
            while start <= end:
                c1 = self.quod(nums[start]); c2 = self.quod(nums[end])
                if self.comp(c1, c2):
                    res[index] = c1
                    start += 1
                else:
                    res[index] = c2
                    end -= 1
                index += step
                
            return res
            
        def quod(self, x):
            return (self.a * x**2) + (self.b * x) + self.c
        
        def comp(self, c1, c2):
            if self.a < 0:
                return c1 < c2
            else:
                return c1 > c2
    

Log in to reply
 

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