• 【算法】使数组有序的最小交换次数


    • 贪心思想,每一步使得对应元素放到它该放的位置。
      • 先将要排序的数组复制一份,然后将其排序,使用哈希表记录排序后的数组对应元素与其对应下标。
      • 遍历原数组与排序后的数组,如果对应下标不相等,则根据哈希表记录该元素的下标进行交换。
    int getMinSwap(vector &nums)
    {
        mapmp;    
        vectorsort_nums(nums);
        sort(sort_nums.begin(),sort_nums.end());
        for (int i = 0; i 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 注意上述代码中,第二个for循环使用的是while,使用if会跳过某些元素。如下图对比。
    • 使用if

    在这里插入图片描述

    • 使用while

    在这里插入图片描述

    int minimumOperations(TreeNode* root) {
            int depth = 0;
            vector>layerContent;
            queueque;
            if(root)que.push(root);
            while(!que.empty()){
                int size = que.size();
                depth++;
                vectortmp;
                for(int i =  0; i < size;i++){
                    TreeNode* node = que.front();
                    que.pop();
                    tmp.push_back(node->val);
                    if(node->left)que.push(node->left);
                    if(node->right)que.push(node->right);
                }
                layerContent.push_back(tmp);
            }
            // 已经获取二叉树的每层元素&层数
            int count = 0;
            for(int i = 1; i < depth;i++){
                count += getMinSwap(layerContent[i]);
            }
            return count;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 相关阅读:
    Linux TC 流量控制介绍
    MP157-0-遇见的问题及解决办法
    提高篇(七):Processing与物联网的结合:如何创建智能互动艺术装置
    网关 Spring Cloud Gateway - API 调用的组织者
    用springboot改写传智健康项目问题
    Spring Boot发送HTML邮件时如何设置模板?
    Flutter 上架如何解决 ITMS-91053 问题
    【深入解析spring cloud gateway】04 Global Filters
    matlab-day04
    Python爬虫获取百度图片+重命名+帧差法获取关键帧
  • 原文地址:https://blog.csdn.net/qq_51604330/article/details/127834394