Easy

题目描述

给你一个由恰好三位数字组成的正整数 n

如果一个数字 n 在经过下面的修改后,结果数字包含数字 1 到 9 恰好一次,并且不包含任何 0,那么我们称这个数字为迷人数字:

n 与数字 2 * n3 * n 连接起来。

如果 n 是迷人数字,则返回 true,否则返回 false

连接两个数字意味着将它们连在一起。例如,121 和 371 的连接是 121371。

示例 1:

输入:n = 192
输出:true
解释:我们将数字 n = 192 和 2 * n = 384 和 3 * n = 576 连接起来。结果数字是 192384576。这个数字包含数字 1 到 9 恰好一次。

示例 2:

输入:n = 100
输出:false
解释:我们将数字 n = 100 和 2 * n = 200 和 3 * n = 300 连接起来。结果数字是 100200300。这个数字不满足任何条件。

约束条件:

  • 100 <= n <= 999

提示:

  • 考虑将数字改变为问题描述中的方式。
  • 检查结果数字是否恰好包含数字 1 到 9 各一次。

解题思路

这道题要求我们判断一个三位数 n 是否是"迷人数字"。解题思路如下:

核心思路:

  1. 将 n、2n、3n 三个数字连接成一个字符串
  2. 检查这个字符串是否恰好包含数字 1-9 各一次,且不包含 0

具体步骤:

  1. 计算 2n 和 3n
  2. 将三个数字转换为字符串并连接
  3. 使用哈希表或数组统计每个数字出现的次数
  4. 验证是否满足条件:字符串长度为9,包含数字1-9各一次,不包含0

优化思路:

  • 由于 n 是三位数(100-999),连接后的字符串长度固定为9位
  • 可以直接检查字符串是否恰好是 “123456789” 的一个排列
  • 使用位掩码或简单的字符计数都可以实现

这是一道典型的字符串处理和哈希表应用题,时间复杂度较低,实现相对简单。

代码实现

class Solution {
public:
    bool isFascinating(int n) {
        string combined = to_string(n) + to_string(2 * n) + to_string(3 * n);
        
        if (combined.length() != 9) return false;
        
        vector<int> count(10, 0);
        for (char c : combined) {
            if (c == '0') return false;
            count[c - '0']++;
        }
        
        for (int i = 1; i <= 9; i++) {
            if (count[i] != 1) return false;
        }
        
        return true;
    }
};
class Solution:
    def isFascinating(self, n: int) -> bool:
        combined = str(n) + str(2 * n) + str(3 * n)
        
        if len(combined) != 9:
            return False
        
        if '0' in combined:
            return False
        
        return set(combined) == set('123456789')
public class Solution {
    public bool IsFascinating(int n) {
        string combined = n.ToString() + (2 * n).ToString() + (3 * n).ToString();
        
        if (combined.Length != 9) return false;
        
        if (combined.Contains('0')) return false;
        
        int[] count = new int[10];
        foreach (char c in combined) {
            count[c - '0']++;
        }
        
        for (int i = 1; i <= 9; i++) {
            if (count[i] != 1) return false;
        }
        
        return true;
    }
}
/**
 * @param {number} n
 * @return {boolean}
 */
var isFascinating = function(n) {
    const concatenated = "" + n + (2 * n) + (3 * n);
    
    if (concatenated.length !== 9) return false;
    if (concatenated.includes('0')) return false;
    
    const digits = new Set(concatenated);
    return digits.size === 9;
};

复杂度分析

复杂度类型复杂度说明
时间复杂度O(1)字符串长度固定为9,所有操作都是常数时间
空间复杂度O(1)使用固定大小的数组或集合存储数字计数