[LeetCode] 2221. Find Triangular Sum of an Array

You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).

The triangular sum of nums is the value of the only element present in nums after the following process terminates:

  1. Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.
  2. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
  3. Replace the array nums with newNums.
  4. Repeat the entire process starting from step 1.

Return the triangular sum of nums.

Example 1:

Input: nums = [1,2,3,4,5]
Output: 8
Explanation:
The above diagram depicts the process from which we obtain the triangular sum of the array.

Example 2:

Input: nums = [5]
Output: 5
Explanation:
Since there is only one element in nums, the triangular sum is the value of that element itself.

Constraints:

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

数组的三角和。

给你一个下标从 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 的三角和。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-triangular-sum-of-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题是关于帕斯卡三角,类似118,119题。遇到这一类的题,基本思路还是把三角形转换成直角三角形做。这道题唯一需要注意的是计算结果需要对 10 取模。

时间O(n^2)

空间O(1) - 直接修改 input 数组

Java实现

 1 class Solution {
 2     public int triangularSum(int[] nums) {
 3         int len = nums.length;
 4         for (int i = len; i > 0; i--) {
 5             for (int j = 1; j < i; j++) {
 6                 nums[j - 1] += nums[j];
 7                 nums[j - 1] %= 10;
 8             }
 9         }
10         return nums[0];
11     }
12 }

 

相关题目

118. Pascal's Triangle

119. Pascal's Triangle II

120. Triangle

799. Champagne Tower

2221. Find Triangular Sum of an Array

LeetCode 题目总结

posted @ 2022-11-20 14:11  CNoodle  阅读(90)  评论(0编辑  收藏  举报