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。

相关推荐
岁忧2 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z2 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码5 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
_Itachi__13 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_78914 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠16 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
dying_man1 天前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel1 天前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
GGBondlctrl1 天前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想