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 1074:元素和为目标值的子矩阵数量
算法·leetcode·矩阵
技术卷2 小时前
详解力扣高频SQL50题之1084. 销售分析 III【简单】
sql·leetcode·oracle
Alfred king2 小时前
面试150 IPO
面试·职场和发展·贪心·数组··排序
设计师小聂!3 小时前
力扣---------238. 除自身以外数组的乘积
数据结构·算法·leetcode
技术卷4 小时前
详解力扣高频SQL50题之550. 游戏玩法分析 IV【中等】
sql·mysql·leetcode·oracle
科大饭桶5 小时前
数据结构自学Day15 -- 非比较排序--计数排序
数据结构·算法·leetcode·排序算法·c
剪一朵云爱着5 小时前
力扣二叉树的前序中序后序遍历总结
算法·leetcode·二叉树
技术卷10 小时前
详解力扣高频 SQL 50 题之584. 寻找用户推荐人【入门】
sql·leetcode·oracle
小徐不徐说10 小时前
每日一算:华为-批萨分配问题
数据结构·c++·算法·leetcode·华为·动态规划·后端开发
草莓熊Lotso16 小时前
【LeetCode刷题指南】--有效的括号
c语言·数据结构·其他·算法·leetcode·刷题