Leetcode 3551. Minimum Swaps to Sort by Digit Sum

  • [Leetcode 3551. Minimum Swaps to Sort by Digit Sum](#Leetcode 3551. Minimum Swaps to Sort by Digit Sum)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上我实现的非常暴力,就是先求出正确的排列,然后从头考察每一个元素是否处在其目标位置上,如果没有,则给出一次置换。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        n = len(nums)
        
        def fn(num):
            return sum(int(digit) for digit in str(num))
        
        index = {x: i for i, x in enumerate(nums)}
        sorted_nums = sorted(nums, key=lambda x: (fn(x), x))

        ans = 0
        for i in range(n):
            if nums[i] == sorted_nums[i]:
                continue
            x, y = nums[i], sorted_nums[i]
            j = index[y]
            nums[i], nums[j] = y, x
            index[x] = j
            index[y] = i
            ans += 1
        return ans

提交代码评测得到:耗时1894ms,占用内存45.8MB。

相关推荐
hn小菜鸡5 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼10 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao10 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试
呆呆的小鳄鱼10 天前
leetcode:98. 验证二叉搜索树
算法·leetcode·职场和发展
alphaTao10 天前
LeetCode 每日一题 2025/6/16-2025/6/22
算法·leetcode