LeetCode 题解工作台

数组的三角和

给你一个下标从 0 开始的整数数组 nums ,其中 nums[i] 是 0 到 9 之间(两者都包含)的一个数字。 nums 的 三角和 是执行以下操作以后最后剩下元素的值: nums 初始包含 n 个元素。如果 n == 1 , 终止 操作。否则, 创建 一个新的下标从 0 开始的长度为 n -…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

我们可以直接模拟题目描述的操作,对数组 进行 $n - 1$ 轮操作,每轮操作都按照题目描述的规则更新数组 。最后返回数组 中剩下的唯一元素即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums ,其中 nums[i] 是 0 到 9 之间(两者都包含)的一个数字。

nums 的 三角和 是执行以下操作以后最后剩下元素的值:

  1. nums 初始包含 n 个元素。如果 n == 1 ,终止 操作。否则,创建 一个新的下标从 0 开始的长度为 n - 1 的整数数组 newNums 。
  2. 对于满足 0 <= i < n - 1 的下标 i ,newNums[i] 赋值 为 (nums[i] + nums[i+1]) % 10 ,% 表示取余运算。
  3. 将 newNums 替换 数组 nums 。
  4. 从步骤 1 开始 重复 整个过程。

请你返回 nums 的三角和。

 

示例 1:

输入:nums = [1,2,3,4,5]
输出:8
解释:
上图展示了得到数组三角和的过程。

示例 2:

输入:nums = [5]
输出:5
解释:
由于 nums 中只有一个元素,数组的三角和为这个元素自己。

 

提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 9
lightbulb

解题思路

方法一:模拟

我们可以直接模拟题目描述的操作,对数组 nums\textit{nums} 进行 n1n - 1 轮操作,每轮操作都按照题目描述的规则更新数组 nums\textit{nums}。最后返回数组 nums\textit{nums} 中剩下的唯一元素即可。

时间复杂度 O(n2)O(n^2),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

数组的三角和题解:数组·数学 | LeetCode #2221 中等