zoukankan      html  css  js  c++  java
  • 边工作边刷题: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]"
                
    
  • 相关阅读:
    servlet程序开发
    jsp九大内置对象
    git原理教程
    jsp基础语法_Scriptlet_基本指令
    06_mysql多表查询
    05_mysql单表查询
    04_mysql增删改操作
    03_mysql索引的操作
    01_mysql数据库操作和基本数据类型
    生成器
  • 原文地址:https://www.cnblogs.com/absolute/p/5815928.html
Copyright © 2011-2022 走看看