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。

相关推荐
草履虫建模11 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头16 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员20 小时前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着2591 天前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
52Hz1181 天前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡1 天前
56.组合总数
数据结构·算法·leetcode
菜鸟233号1 天前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划
LiLiYuan.1 天前
【Cursor 中找不到LeetCode 插件解决办法】
算法·leetcode·职场和发展
Charlie_lll1 天前
力扣解题-[3379]转换数组
数据结构·后端·算法·leetcode