边工作边刷题:70天一遍leetcode: day 97-1
Sort Transformed Array
要点:
知道了解法就容易了:本质:如何把一个单调的转化成双向单调的:结构包括两部分:原array的选择方向(双指针)和填结果array的方向。
- min/max在input sorted array的中间点,所以双向验证,另外根据开口方向,决定从两边走是越来越大还是越来越小决定从那边填结果array。
- a==0的情况可以和a>0的情况相同:因为变成单调的,无论升降,都是某一边一直占优势,所以和a>0或a<0没差别。
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]"
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步