1122. Relative Sort Array*

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值