边工作边刷题:70天一遍leetcode: day 97-1

Sort Transformed Array

要点:
知道了解法就容易了:本质:如何把一个单调的转化成双向单调的:结构包括两部分:原array的选择方向(双指针)和填结果array的方向。

  • min/max在input sorted array的中间点,所以双向验证,另外根据开口方向,决定从两边走是越来越大还是越来越小决定从那边填结果array。
  • a==0的情况可以和a>0的情况相同:因为变成单调的,无论升降,都是某一边一直占优势,所以和a>0或a<0没差别。

https://repl.it/C9tc/1

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]
        """
        def calRes(num):
            return a*num*num + b*num + c
        
        n = len(nums)
        res = []
        i,j = 0, n-1
        if a>=0:
            while i<=j:
                x, y = calRes(nums[i]), calRes(nums[j])
                if x>=y:
                    res.append(x)
                    i+=1
                else:
                    res.append(y)
                    j-=1
            return res[::-1]
        else:
            while i<=j:
                x, y = calRes(nums[i]), calRes(nums[j])
                if x<=y:
                    res.append(x)
                    i+=1
                else:
                    res.append(y)
                    j-=1
            return res

sol = Solution()
assert sol.sortTransformedArray([-4,-2,2,4], 1,3,5)==[3,9,15,33], "result should be [3,9,15,33]"
            
posted @ 2016-07-07 20:45  absolute100  阅读(100)  评论(0编辑  收藏  举报