博客
关于我
LeetCode 1122 数组的相对排序-简单-unordered_map容器的应用
阅读量:489 次
发布时间:2019-03-06

本文共 2250 字,大约阅读时间需要 7 分钟。

    
Relative Sort Arrays

Relative Sort Arrays Problem

Given two arrays, arr1 and arr2, where each element in arr2 is unique and appears in arr1, we need to sort arr1 such that the relative order of elements matches arr2. Elements not present in arr2 should be placed at the end 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]

Approach

To solve this problem, we can follow these steps:

  • Mapping Elements: First, create a mapping of each element in arr2 to its position. This helps in determining the required order of elements in arr1.
  • Sorting arr1: Sort the elements in arr1 based on their positions in arr2. Elements not present in arr2 are placed at the end in ascending order.

Implementation Steps

In code, we can implement this using a hash table (unordered_map) to store the positions of elements in arr2. Then, sort arr1 using a custom comparator that checks the positions from arr2. Finally, append any elements from arr1 that are not in arr2, sorted in ascending order.

Code Example

class Solution {public:    vector
relativeSortArray(vector
& arr1, vector
& arr2) { unordered_map
positionMap; // Populate the position map for (int i = 0; i < arr2.size(); ++i) { positionMap[arr2[i]] = i; } // Sort arr1 based on the position map sort(arr1.begin(), arr1.end(), [&positionMap](int a, int b) { return positionMap[a] < positionMap[b]; }); // Append elements from arr1 not present in arr2, sorted vector
extra; for (int num : arr1) { if (positionMap.find(num) == positionMap.end()) { extra.push_back(num); } } sort(extra.begin(), extra.end()); arr1.insert(arr1.end(), extra.begin(), extra.end()); return arr1; }

转载地址:http://ephdz.baihongyu.com/

你可能感兴趣的文章
Objective-C实现在指定区间 [a, b] 中找到函数的实根,其中 f(a)*f(b) < 0算法(附完整源码)
查看>>
Objective-C实现均值滤波(附完整源码)
查看>>
Objective-C实现埃拉托斯特尼筛法算法(附完整源码)
查看>>
Objective-C实现域名解析(附完整源码)
查看>>
Objective-C实现域名转IP(附完整源码)
查看>>
Objective-C实现培根密码算法(附完整源码)
查看>>
Objective-C实现基于 LIFO的堆栈算法(附完整源码)
查看>>
Objective-C实现基于 LinkedList 的添加两个数字的解决方案算法(附完整源码)
查看>>
Objective-C实现基于opencv的抖动算法(附完整源码)
查看>>
Objective-C实现基于事件对象实现线程同步(附完整源码)
查看>>
Objective-C实现基于信号实现线程同步(附完整源码)
查看>>
Objective-C实现基于文件流拷贝文件(附完整源码)
查看>>
Objective-C实现基于模板的双向链表(附完整源码)
查看>>
Objective-C实现基于模板的顺序表(附完整源码)
查看>>
Objective-C实现基本二叉树算法(附完整源码)
查看>>
Objective-C实现堆排序(附完整源码)
查看>>
Objective-C实现填充环形矩阵(附完整源码)
查看>>
Objective-C实现声音录制播放程序(附完整源码)
查看>>
Objective-C实现备忘录模式(附完整源码)
查看>>
Objective-C实现复制粘贴文本功能(附完整源码)
查看>>