LeetCode 题解工作台

替换为数位和以后的最小元素

给你一个整数数组 nums 。 请你将 nums 中每一个元素都替换为它的各个数位之 和 。 请你返回替换所有元素以后 nums 中的 最小 元素。 示例 1: 输入: nums = [10,12,13,14] 输出: 1 解释: nums 替换后变为 [1, 3, 4, 5] ,最小元素为 1 。…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们可以遍历数组 ,对于每个数 ,我们计算其各个数位之和 ,取所有 中的最小值即为答案。 时间复杂度 $O(n \times \log M)$,其中 和 分别是数组 的长度和数组中的最大值。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 。

请你将 nums 中每一个元素都替换为它的各个数位之  。

请你返回替换所有元素以后 nums 中的 最小 元素。

 

示例 1:

输入:nums = [10,12,13,14]

输出:1

解释:

nums 替换后变为 [1, 3, 4, 5] ,最小元素为 1 。

示例 2:

输入:nums = [1,2,3,4]

输出:1

解释:

nums 替换后变为 [1, 2, 3, 4] ,最小元素为 1 。

示例 3:

输入:nums = [999,19,199]

输出:10

解释:

nums 替换后变为 [27, 10, 19] ,最小元素为 10 。

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 104
lightbulb

解题思路

方法一:模拟

我们可以遍历数组 nums\textit{nums},对于每个数 xx,我们计算其各个数位之和 yy,取所有 yy 中的最小值即为答案。

时间复杂度 O(n×logM)O(n \times \log M),其中 nnMM 分别是数组 nums\textit{nums} 的长度和数组中的最大值。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def minElement(self, nums: List[int]) -> int:
        return min(sum(int(b) for b in str(x)) for x in nums)
speed

复杂度分析

指标
时间complexity is O(n * k), where n is the array length and k is the number of digits in the largest number. Space complexity can be O(1) if using a running minimum without storing the transformed array.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They may ask how to efficiently compute the digit sum without converting to string.

  • question_mark

    Expect questions on handling edge cases like single-digit numbers or maximum constraints.

  • question_mark

    They might test optimization for in-place minimum calculation versus storing intermediate results.

warning

常见陷阱

外企场景
  • error

    Forgetting to replace all numbers before computing the minimum can yield incorrect results.

  • error

    Incorrectly summing digits by assuming fixed-length numbers instead of iterating through all digits.

  • error

    Using extra arrays unnecessarily when a running minimum suffices, increasing space complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of the minimum, return the maximum element after digit sum replacement.

  • arrow_right_alt

    Apply the digit sum replacement repeatedly until all numbers are single-digit, then return the minimum.

  • arrow_right_alt

    Replace only numbers above a certain threshold with their digit sum and return the smallest value.

help

常见问题

外企场景

替换为数位和以后的最小元素题解:数组·数学 | LeetCode #3300 简单