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。

相关推荐
夏鹏今天学习了吗1 天前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实1 天前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
轮到我狗叫了1 天前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
熬了夜的程序员1 天前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman1 天前
LeetCode Hot100 自用
算法·leetcode·职场和发展
还是码字踏实1 天前
算法题种类与解题思路全面指南:基于LeetCode Hot 100与牛客Top 101
算法·leetcode
熬了夜的程序员1 天前
【LeetCode】101. 对称二叉树
算法·leetcode·链表·职场和发展·矩阵
Kuo-Teng2 天前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
葵续浅笑2 天前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode