1122. Relative Sort Array*

北战南征 提交于 2019-12-26 15:42:37

1122. Relative Sort Array*

https://leetcode.com/problems/relative-sort-array/

题目描述

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don’t appear in arr2 should be placed at the end of arr1 in ascending order.

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.

C++ 实现 1

发现做题啊, 不要一开始就想怎么找出最优解法, 第一要务还是将题解出来再说, 各种数据结构直接上. 后来发现, 所用空间 beats 100%. 这题一开始如果我拒绝用其他的数据结构, 可能就做不出来了.

思路是: 统计 arr1 中每个元素的个数, 然后将 arr2 中出现过的元素依次放置在 arr1 的前面; 并清空 records 个数为 0 的元素. 将剩余元素放在 tmp 中, 排序后拷贝到 arr1 中.

class Solution {
public:
    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
        unordered_map<int, int> records;
        vector<int> tmp;
        int k = 0;
        for (auto &i : arr1) records[i] ++;
        for (int i = 0; i < arr2.size(); ++i) {
            while (records[arr2[i]]--)
                arr1[k++] = arr2[i];
            records.erase(arr2[i]);
        }
        for (auto &p : records)
            while (p.second--)
                tmp.push_back(p.first);
        std::sort(tmp.begin(), tmp.end());
        for (int i = 0; i < tmp.size(); ++i) {
            arr1[k++] = tmp[i];
        }
        return arr1;
    }
};

C++ 实现 2

LeetCode Submission 还看到一种解法, 以后再研究.

class Solution {
public:
    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
        if(arr1.empty()) return arr1;
        unordered_map<int, int> mp;
        for(int i = 0; i < arr2.size(); ++i) mp[arr2[i]] = i;
        sort(arr1.begin(), arr1.end(), 
             [&mp](const int lhs, const int rhs) {
                if(mp.count(lhs) && mp.count(rhs)) {
                    return mp[lhs] < mp[rhs];
                }
                else if(mp.count(lhs) || mp.count(rhs))
                    return mp.count(lhs) ? true : false;
                else
                    return lhs < rhs;
             });
        return arr1;
    }
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!