当前位置:网站首页>LeetCode中等题之旋转函数
LeetCode中等题之旋转函数
2022-04-23 07:02:00 【·星辰大海】
题目
给定一个长度为 n 的整数数组 nums 。
假设 arrk 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数 F 为:
F(k) = 0 * arrk[0] + 1 * arrk[1] + … + (n - 1) * arrk[n - 1]
返回 F(0), F(1), …, F(n-1)中的最大值 。
生成的测试用例让答案符合 32 位 整数。
示例 1:
输入: nums = [4,3,2,6]
输出: 26
解释:
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
示例 2:
输入: nums = [100]
输出: 0
提示:
n == nums.length
1 <= n <= 10^5
-100 <= nums[i] <= 100
来源:力扣(LeetCode)
解题思路
题目的做法比较易懂,按照示例1的意思就是下标不动数组每个元素右移或者元素不动,下标左移,我们任取一种固定另外一种就可以完成题目的要求。
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
index=deque([i for i in range(len(nums))]) #旋转下标
MAX=-float('inf')
for i in range(len(nums)):
s=0
for j in range(len(nums)):
s+=nums[j]*index[j]
if s>MAX:
MAX=s
index.append(index.popleft()) #下标左移
return MAX
很明显每次都计算全部的数组和其下标,复杂度是O(n^2)所以非常容易超时,因此我们需要利用数学上的方法使得计算量减少,没有思路的话可以在纸上写写划划,当我们将F(0),F(1)的表达式写出来的时候就会发现,这其实就是高中前n项和常用的手段,高斯当年计算的精华错位相减。
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
s,MAX,S,k=0,-float('inf'),sum(nums),1
for i,j in enumerate(nums):
s+=i*j
for i in range(len(nums)):
if s>MAX:
MAX=s
s+=S-len(nums)*nums[-k]
k+=1
return MAX
版权声明
本文为[·星辰大海]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_18560985/article/details/124352987
边栏推荐
- CSV Column Extract列提取
- 以下程序实现从字符串str中删除第i个字符开始的连续n个字
- js将树形结构数据转为一维数组数据
- Cloud computing skills competition -- the first part of openstack private cloud environment
- C 输出一种二维数组,特点如下。
- 数据库之MySQL——基本常用查询命令
- LeetCode15. 三数之和
- 华硕笔记本电脑重装系统后不能读取usb,不能上网
- Research on system and software security (I)
- Distributed service governance Nacos
猜你喜欢
How to import Excel data in SQL server, 2019 Edition
几种智能机器人室内定位方法对比
dried food! Point based: differentiable Poisson solver
Thinkphp6 + JWT realizes login verification
Intranet penetration series: pingtunnel of Intranet tunnel
Mobile terminal layout (3D conversion, animation)
Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
How does feign integrate hystrix
惨了,搞坏了领导的机密文件,吐血分享备份文件的代码技巧
BUUCTF [ACTF2020 新生赛]Include1
随机推荐
[problem solving] vs2019 solves the problem that the EXE file generated by compilation cannot be opened
Research on system and software security (2)
[极客大挑战 2019]Havefun1
BUUCTF [ACTF2020 新生赛]Include1
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
Asynchronous learning
求3个字符串(每串不超过20个字符)中的最大者。
简述CPU
js常用数组方法
NIH降血脂指南《your guide to lowering your Cholesterol with TLC》笔记(持续更新中)
nn.Module类的讲解
输入 “ net start mysql ”,出现 “ 发生系统错误 5。 拒绝访问 ” 。问题详解
Go语学习笔记 - 异常处理 | 从零开始Go语言
Anti shake and throttling
巨头押注的全屋智能,正在驱动海信、华为、小米们「自我革命」
Why are there 1px problems? How?
Research on system and software security (I)
C 输出一种二维数组,特点如下。
Implementation of new
LeetCoed18. 四数之和