LeetCode | 1122. Relative Sort Array

it2022-05-05  151

 

题外话:

刚看完《大空头》,趁着感慨+激动刷个题~ 最近Leetcode更新题目的频率已经完全超出了做题的速度= =

 

题目:

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 <= 10000 <= arr1[i], arr2[i] <= 1000Each arr2[i] is distinct.Each arr2[i] is in arr1.

 

解题思路:

首先解读题意。arr2的元素都是独一无二的,并且都所属于arr1。arr1中可能包含重复元素。目标是将arr1中的元素重新排序,排序规则是1)属于arr2的元素(part1)排序先于arr1其余不属于arr2的元素(part2);2)part1中arr1元素的顺序与arr2的元素顺序保持一致,part2的元素按照升序排列。

然后考虑边界情况,arr2元素为空时,直接返回排序的arr1;通常情况,根据arr2对arr1进行遍历,若arr1元素arr1[j]等于当前扫描的arr2的元素arr2[i],则与数组元素置换,num_idx记录已置换排好序的元素个数,即排序好的arr1的索引。遍历之后,对arr1剩余元素arr1[num_idx:end]进行排序。解法复杂度为O(m*n+n*log n),m为arr2的长度,n为arr1的数组长度。

 

代码:

class Solution { public: vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) { if(arr2.size() < 1) { sort(arr1.begin(), arr1.end()); return arr1; } int num_idx = 0; for(int i = 0; i < arr2.size(); i++) { for(int j = num_idx; j < arr1.size(); j++) { if(arr2[i] == arr1[j]) { swap(arr1[j], arr1[num_idx]); num_idx++; } } } sort(arr1.begin()+num_idx, arr1.end()); return arr1; } };

 

一次AC~ 太久没写C++ >.<

 

 

 

 


最新回复(0)