• 1122. Relative Sort Array


    问题:

    给定数组arr2,所含元素唯一,

    给定数组arr1,对arr1排序,使得arr1的元素相对顺序为arr2的顺序,不存在于arr2中的元素,按照升序排列。

    Example 1:
    Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
    Output: [2,2,2,1,4,3,3,9,6,7,19]
     
    
    Constraints:
    arr1.length, arr2.length <= 1000
    0 <= arr1[i], arr2[i] <= 1000
    Each arr2[i] is distinct.
    Each arr2[i] is in arr1.
    

      

    解法:

    由于限制:所有元素大小:0 <= arr1[i], arr2[i] <= 1000

    因此可以考虑使用桶排序。

    计数arr1中每个元素出现的次数ncout[],

    首先,根据arr2的元素,遍历,输出ncout[a2]个a2,

    同时更新ncout[a2]=0,

    再次,遍历ncout,输出计数不为0的元素。

    代码参考:

     1 class Solution {
     2 public:
     3     vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
     4         vector<int> res;
     5         int ncout[1001]={0};
     6         for(int a1:arr1){
     7             ncout[a1]++;
     8         }
     9         for(int a2:arr2){
    10             if(ncout[a2]>0){
    11                 vector<int> tmp(ncout[a2], a2);
    12                 res.insert(res.end(), tmp.begin(), tmp.end());
    13                 ncout[a2]=0;
    14             }
    15         }
    16         for(int i=0; i<1001; i++){
    17             if(ncout[i]>0){
    18                 vector<int> tmp(ncout[i], i);
    19                 res.insert(res.end(), tmp.begin(), tmp.end());
    20             }
    21         }
    22         return res;
    23     }
    24 };

    另,不使用vector合并insert方法,使用push_back的时候:

    但这时花费memory大于上面的合并vector方法。

     1 class Solution {
     2 public:
     3     vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
     4         vector<int> res;
     5         int ncout[1001]={0};
     6         for(int a1:arr1){
     7             ncout[a1]++;
     8         }
     9         for(int a2:arr2){
    10             while(ncout[a2]>0){
    11                 res.push_back(a2);
    12                 ncout[a2]--;
    13             }
    14         }
    15         for(int i=0; i<1001; i++){
    16             while(ncout[i]>0){
    17                 res.push_back(i);
    18                 ncout[i]--;
    19             }
    20         }
    21         return res;
    22     }
    23 };
  • 相关阅读:
    borderInterpolate()函数
    cvtColor(src, src_gray, CV_BGR2GRAY)报错
    用OpenCV读取摄像头
    OpenCV的视频输入和相似度测量
    C++ main函数中参数argc和argv含义及用法
    OpenCV的视频读取
    MySql与Oracle的几个主要区别
    OLTP与OLAP的介绍(理论知识)
    IDEA激活
    short i =1; i=i+1与short i=1; i+=1的区别
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13167565.html
Copyright © 2020-2023  润新知