LeetCode 题解工作台

反转之后不同整数的数目

给你一个由 正 整数组成的数组 nums 。 你必须取出数组中的每个整数, 反转其中每个数位 ,并将反转后得到的数字添加到数组的末尾。这一操作只针对 nums 中原有的整数执行。 返回结果数组中 不同 整数的数目。 示例 1: 输入: nums = [1,13,10,12,31] 输出: 6 解释:…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们先用哈希表记录数组中的所有整数,然后遍历数组中的每个整数,对其进行反转,将反转后的整数添加到哈希表中,最后返回哈希表的大小即可。 时间复杂度 ,空间复杂度 。其中 是数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 整数组成的数组 nums

你必须取出数组中的每个整数,反转其中每个数位,并将反转后得到的数字添加到数组的末尾。这一操作只针对 nums 中原有的整数执行。

返回结果数组中 不同 整数的数目。

 

示例 1:

输入:nums = [1,13,10,12,31]
输出:6
解释:反转每个数字后,结果数组是 [1,13,10,12,31,1,31,1,21,13] 。
反转后得到的数字添加到数组的末尾并按斜体加粗表示。注意对于整数 10 ,反转之后会变成 01 ,即 1 。
数组中不同整数的数目为 6(数字 1、10、12、13、21 和 31)。

示例 2:

输入:nums = [2,2,2]
输出:1
解释:反转每个数字后,结果数组是 [2,2,2,2,2,2] 。
数组中不同整数的数目为 1(数字 2)。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 106
lightbulb

解题思路

方法一:哈希表

我们先用哈希表记录数组中的所有整数,然后遍历数组中的每个整数,对其进行反转,将反转后的整数添加到哈希表中,最后返回哈希表的大小即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组的长度。

1
2
3
4
5
6
7
8
class Solution:
    def countDistinctIntegers(self, nums: List[int]) -> int:
        s = set(nums)
        for x in nums:
            y = int(str(x)[::-1])
            s.add(y)
        return len(s)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate understands how to handle uniqueness using hash-based data structures.

  • question_mark

    Candidate demonstrates efficient handling of large input sizes (up to 10^5).

  • question_mark

    Candidate can optimize for both time and space complexity, particularly in managing distinct elements.

warning

常见陷阱

外企场景
  • error

    Forgetting to reverse the digits properly, especially for numbers like 10 or 100 that result in leading zeros.

  • error

    Not using a data structure like a set or hash table to track distinct elements, leading to incorrect results.

  • error

    Misunderstanding the problem constraints and assuming a more complex solution when a set or hash table suffices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handle negative numbers by modifying the digit reversal approach.

  • arrow_right_alt

    Consider using a different data structure for tracking distinct elements, such as an array with sorting.

  • arrow_right_alt

    Extend the problem to handle larger input sizes or multiple operations (e.g., repeated reversals).

help

常见问题

外企场景

反转之后不同整数的数目题解:数组·哈希·扫描 | LeetCode #2442 中等