Relative Sort Array
程序员文章站
2023-11-12 09:09:58
"Relative Sort Array" Example 1: Constraints: arr1.length, arr2.length include include using namespace std; class Solution { public: vector relativeSo ......
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
参考文献
上一篇: Illustrator绘制一个停止图标
下一篇: PHP生成Gif图片验证码
推荐阅读
-
php计算数组相同值出现次数的代码(array_count_values)
-
JavaScript引用类型之Array类型API详解
-
numpy返回array中元素的index方法
-
详谈js遍历集合(Array,Map,Set)
-
css position: absolute、relative详解
-
PHP排序算法之堆排序(Heap Sort)实例详解
-
PHP排序算法之归并排序(Merging Sort)实例详解
-
PHP排序算法之基数排序(Radix Sort)实例详解
-
Python过滤掉numpy.array中非nan数据实例
-
python 解决mysql where in 对列表(list,,array)问题