LeetCode 题解工作台
数组的三角和
给你一个下标从 0 开始的整数数组 nums ,其中 nums[i] 是 0 到 9 之间(两者都包含)的一个数字。 nums 的 三角和 是执行以下操作以后最后剩下元素的值: nums 初始包含 n 个元素。如果 n == 1 , 终止 操作。否则, 创建 一个新的下标从 0 开始的长度为 n -…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们可以直接模拟题目描述的操作,对数组 进行 $n - 1$ 轮操作,每轮操作都按照题目描述的规则更新数组 。最后返回数组 中剩下的唯一元素即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,其中 nums[i] 是 0 到 9 之间(两者都包含)的一个数字。
nums 的 三角和 是执行以下操作以后最后剩下元素的值:
nums初始包含n个元素。如果n == 1,终止 操作。否则,创建 一个新的下标从 0 开始的长度为n - 1的整数数组newNums。- 对于满足
0 <= i < n - 1的下标i,newNums[i]赋值 为(nums[i] + nums[i+1]) % 10,%表示取余运算。 - 将
newNums替换 数组nums。 - 从步骤 1 开始 重复 整个过程。
请你返回 nums 的三角和。
示例 1:

输入:nums = [1,2,3,4,5] 输出:8 解释: 上图展示了得到数组三角和的过程。
示例 2:
输入:nums = [5] 输出:5 解释: 由于 nums 中只有一个元素,数组的三角和为这个元素自己。
提示:
1 <= nums.length <= 10000 <= nums[i] <= 9
解题思路
方法一:模拟
我们可以直接模拟题目描述的操作,对数组 进行 轮操作,每轮操作都按照题目描述的规则更新数组 。最后返回数组 中剩下的唯一元素即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def triangularSum(self, nums: List[int]) -> int:
for k in range(len(nums) - 1, 0, -1):
for i in range(k):
nums[i] = (nums[i] + nums[i + 1]) % 10
return nums[0]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of iterative processes in arrays.
- question_mark
Check for awareness of space optimization techniques in array manipulation.
- question_mark
Evaluate familiarity with time complexity reductions and efficient problem-solving.
常见陷阱
外企场景- error
Failing to correctly simulate the process by not updating the array properly in each step.
- error
Not optimizing for space by using an additional array when the process can be done in-place.
- error
Overcomplicating the solution by attempting to handle the problem in a more complex way when a simple iterative approach works.
进阶变体
外企场景- arrow_right_alt
Different array sizes could be tested, from the smallest case with one element to the largest with 1000 elements.
- arrow_right_alt
Modifying the problem to use elements larger than 9 to test how the solution handles different ranges of numbers.
- arrow_right_alt
Introducing more complex operations between elements (such as subtraction or multiplication) could test the adaptability of the algorithm.