当前位置:网站首页>Leetcode每日一题396. 旋转函数
Leetcode每日一题396. 旋转函数
2022-04-22 20:18:00 【小羊努力变强】
写在前面
本篇内容:Leetcode每日一题396. 旋转函数
文章专栏:leetcode每日一题《打卡日常》
算法仓库:小的变强之路
题目
给定一个长度为 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 <= 105
-100 <= nums[i] <= 100
思路
迭代+数学
记数组 nums 的元素之和为 numSum。根据公式,可以得到:
F(0)=0×nums[0]+1×nums[1]+…+(n−1)×nums[n−1]
F(1)=1×nums[0]+2×nums[1]+…+0×nums[n−1]=F(0)+numSum−n×nums[n−1]+
更一般地,当 1≤k<n 时,F(k)=F(k−1)+numSum−n×nums[n−k]。我们可以不停迭代计算出不同的 F(k),并求出最大值。
代码实现
class Solution {
public:
int maxRotateFunction(vector<int>& nums) {
int f = 0, n = nums.size();
int numSum = accumulate(nums.begin(), nums.end(), 0);
for (int i = 0; i < n; i++) {
f += i * nums[i];
}
int res = f;
for (int i = n - 1; i > 0; i--) {
f += numSum - n * nums[i];
res = max(res, f);
}
return res;
}
};
复杂度分析
时间复杂度:O(n),其中 n 是数组 nums 的长度。计算 numSum 和第一个 f 消耗 O(n) 时间,后续迭代 n−1 次 f 消耗 O(n) 时间。
空间复杂度:O(1)。仅使用常数空间。
写在最后
觉得本篇文章不错的话记得点赞,收藏,还有问题也可以评论留言
你的支持将是我继续创作的最大动力️️️
由于作者水平有限,如有错误和不准确之处在所难免,本人也很想知道这些错误,恳望读者批评指正!
版权声明
本文为[小羊努力变强]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_54847231/article/details/124353874
边栏推荐
猜你喜欢

Markdown learning

掌握这些引用参考文献的小Tips,助您论文写作事半功倍~

Filebeat

重保战场的“排头兵”,“互联网宙斯盾”如何为城市高效布防?

文件上传问题记录

Problems that must be avoided in the process of top survey technology sorting and transformation

Perfect forwarding implementation mechanism

ZTNA (Zero Trust Network Access)

Solve the problem of log printing when kingbasees inserts data into PG mode stand-alone database

Comparison and principle summary of golang local cache selection
随机推荐
Is it better to do operation or software testing?
396. 旋转函数(数学规律 + 迭代法)
mysql经纬度 某半径长度 内查询数据
FPGA中的D触发器
什么是浏览器同源策略?
Detailed tutorial on installing MySQL 8.0 + eclipse configuration under Linux
2022年土建施工员题库精准小题库建设厅施工员
Acrobat Pro DC tutorial, how to use password to protect PDF files?
[recent function update] seamless experience free demo!
如何提高PHP编程的效率?
【Unity】可玩广告Luna Playable插件的踩坑记录
The most complete interpretation of redis
金仓数据库KingbaseES的连接方法
Where should 2021 fresh graduates go?
Academician Mei Hong: how to construct artificial swarm intelligence
掌握这些引用参考文献的小Tips,助您论文写作事半功倍~
域名解析过程
STM32 uses USB virtual serial port + ymodem to upgrade IAP
时间戳转换
Some considerations for pointers and objects