C++ algorithm learning (Like: 1122. Relative sorting of arrays)

Gives you two arrays, arr1 and arr2,

The elements in
arr2 are different. Each element in arr2 appears in arr1.
Sort the elements in arr1 so that the relative order of the items in arr1 is the same as the relative order in arr2. Elements that have not appeared in arr2 need to be placed at the end of arr1 in ascending order.

Example:

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]

prompt:

arr1.length, arr2.length <= 1000 0 <= arr1[i], arr2[i] <= 1000
The elements in arr2 arr2[i] are different. Each element in arr2 arr2[i] appears in arr1 in

Source: LeetCode
Link: https://leetcode-cn.com/problems/relative-sort-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

To get the question, first of all we need to know that this question is a sorted array, and it is weighted according to the order in arr2. What we compare is not the data of arr1, but the data size of arr2, but the data of arr1 is filled in. So I thought of using map. In map, using unordered_map is faster.

See my notes for details.

class Solution {
    
    
public:
    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
    
    
     unordered_map<int,int> umap;
     for(int i = 0;i<arr2.size();i++){
    
    
         umap[arr2[i]] = i;
         //把数据进行加权
     }
     //加完权以后我们可以把数据进行比较了
     sort(arr1.begin(), arr1.end(), [&](int x, int y){
    
    
    //如果x,y都在arr2中出现,那么比较x,y在umap里的权值,如果x在里面,y不在里面,那么x就是大的
    if(umap.count(x)!=0) return (umap.count(y)!=0) ? umap[x] < umap[y] : true;
    //如果x不在,y在,那么y是大的,如果x和y都不在,就直接比较x和y本身大小。
    else return (umap.count(y)!=0) ? false : x<y;
     });
     return arr1;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109687589