Relative Sort Array
2019-08-16 07:51:08来源:博客园 阅读 ()
Relative Sort Array
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.
Code
//
// main.cpp
// 按照字符串2对字符串1进行排序
//
// Created by mac on 2019/7/20.
// Copyright ? 2019 mac. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
vector<int> arr3,arr4;
for (int i=0;i<arr2.size() ; ++i) {
for (int j=0; j<arr1.size(); ++j) {
if (arr1[j]==arr2[i]) {
arr3.push_back(arr2[i]);
arr1[j]=1001;
}
}
}
vector<int>::iterator it=arr1.begin();
while (it!=arr1.end()) {
if (*it!=1001) {
arr4.push_back(*it);
}
it++;
}
sort(arr4.begin(), arr4.end());
for (int j=0; j<arr4.size(); ++j) {
arr3.push_back(arr4[j]);
}
return arr3;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
vector<int> arr1,arr2,arr;
arr1={2,3,1,3,2,4,6,7,9,2,19};
arr2={2,1,4,3,9,6};
Solution so;
arr=so.relativeSortArray(arr1, arr2);
for (int i=0; i<arr.size(); ++i) {
cout<<arr[i]<<" ";
}
cout<<endl;
// [2,3,1,3,2,4,6,7,9,2,19]
// [2,1,4,3,9,6]
return 0;
}
运行结果
2 2 2 1 4 3 3 9 6 7 19
Program ended with exit code: 0
参考文献
- https://leetcode.com/problems/relative-sort-array/
原文链接:https://www.cnblogs.com/overlows/p/11219563.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:扫描线——POJ1151
- C++ 模板类array 2020-05-31
- CountingSort(计数排序)原理及C++代码实现 2020-01-14
- MergeSort(归并排序)原理及C++代码实现 2020-01-14
- InsertionSort(插入排序)原理及C++代码实现 2020-01-14
- 操作符重载(二) 2019-09-30
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash