• 边工作边刷题: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]"
                
    
  • 相关阅读:
    观察者模式
    工厂模式
    单例模式
    代理模式
    策略模式
    Ioc容器
    Spring概述
    02:入门
    01:背景
    编译原理感悟
  • 原文地址:https://www.cnblogs.com/absolute/p/5815928.html
Copyright © 2020-2023  润新知