20.11.14 leetcode1122(自定义排序)

题目链接:https://leetcode-cn.com/problems/relative-sort-array/

又是一个简单题,懒得多说了,我用的暴力,有价值的地方就是题解用的这种自定义排序的方法, 之前没写过这样的自定义排序,码住。

class Solution {
public:
    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
        unordered_map<int, int> rank;
        for (int i = 0; i < arr2.size(); ++i) {
            rank[arr2[i]] = i;
        }
        sort(arr1.begin(), arr1.end(), [&](int x, int y) {
            if (rank.count(x)) {
                return rank.count(y) ? rank[x] < rank[y] : true;
            }
            else {
                return rank.count(y) ? false : x < y;
            }
        });
        return arr1;
    }
};
原文地址:https://www.cnblogs.com/qingjiuling/p/13973719.html