Leetcode3265. 统计近似相等数对 I

Every day a Leetcode

题目来源:3265. 统计近似相等数对 I

解法1:枚举

暴力枚举数组 nums 中下标 i 和 j 满足 i < j 的 nums[i] 和 nums[j],判断它们是否近似相等。

细节:先对数组 nums 升序排序,在判断它们是否近似相等,转成字符串进行比较,且只交换较大数的数位。

代码:

/*
 * @lc app=leetcode.cn id=3265 lang=cpp
 *
 * [3265] 统计近似相等数对 I
 */

// @lc code=start
class Solution
{
public:
    int countPairs(vector<int> &nums)
    {
        int n = nums.size();
        sort(nums.begin(), nums.end());

        int ans = 0;
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (check(to_string(nums[i]), to_string(nums[j])))
                    ans++;
        return ans;
    }
    // 辅函数
    bool check(string s1, string s2)
    {
        if (stoi(s1) == stoi(s2))
            return true;
        int len2 = s2.length();
        for (int i = 0; i < len2 - 1; i++)
            for (int j = i + 1; j < len2; j++)
            {
                swap(s2[i], s2[j]); // 交换数位
                if (stoi(s1) == stoi(s2))
                    return true;
                else
                {
                    // 记得复原
                    swap(s2[i], s2[j]);
                }
            }
        return false;
    }
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(nlogn + n2 * len(max(nums))2),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值