zoukankan      html  css  js  c++  java
  • 1030 距离顺序排列矩阵单元格 重要

    get到的新知识点

    • vector定义二维数组
      • vector<vector<int>>rec(R*C,vector<int>(3))//定义一个vector变量rec,总共包含R*C个vector变量,rec由很多个vector变量组成,每一个vector大小是3,前两个存放坐标,第三个存放曼哈顿距离,相当于一个二维数组,[[0,0,1],[0,0,2]]
    • sort条件排序
      • sort(begin,end,cmp)
      • cmp是排序机制,默认是升序排列,可以自己编写cmp函数
      • static bool function(vector<int> &a,vector<int> &b)//排序函数
               {
                return a[2]<b[2];
                }

    思路

    • 计算出曼哈顿距离存放在vector变量的第三个位置中,然后利用sort函数排序,自己写出排序条件,条件是按照vector变量中第三个数升序排列

    代码

    •  1 class Solution {
       2 public:
       3     vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
       4         vector<vector<int>>rec(R*C,vector<int>(3));
       5         int num=0;
       6         for(int i=0;i<R;i++){
       7             for(int j=0;j<C;j++){
       8                 rec[num][0]=i;
       9                 rec[num][1]=j;
      10                 rec[num][2]=abs(r0-i)+abs(c0-j);
      11                 num++;
      12             }
      13         }
      14         
      15         sort(rec.begin(),rec.end(),function);
      16         for(int i=0;i<rec.size();i++){//最后要把距离值删掉,输出点
      17             rec[i].pop_back();
      18         }
      19         return rec;
      20     }
      21     static bool function(vector<int> &a,vector<int> &b)//排序函数
      22         {
      23         return a[2]<b[2];
      24         }
      25 };

      到这里排序的简单题就做完啦!!

  • 相关阅读:
    【js】replace()
    【js】indexOf()
    【js】sort()
    【js】typeof与instanceof
    【js】with 语句
    跳出框架iframe的操作语句
    Mongodb启动命令mongod参数说明
    ERROR: child process failed, exited with error number 100
    SELECT控件add方法 ie 类型不匹配
    Red hat linux ping: unknown host www.baidu.com
  • 原文地址:https://www.cnblogs.com/hehesunshine/p/11688474.html
Copyright © 2011-2022 走看看