[LeetCode] 1122. 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.

数组的相对排序。题意是给两个数组arr1和arr2,arr1较长,有重复元素;arr2较短,没有重复元素;arr2中所有元素都在arr1中出现。请对arr1中的元素进行排序,使arr1中所有元素的相对顺序和arr2中的相对顺序相同。未在arr2中出现过的元素需要按照升序放在arr1的末尾。注意有一个限制条件是数组长度不超过1000。

思路是用counting sort(计数排序)做,用一个长度为1001(Java需要定义长度)的数组(bucket)记录每个数字在arr1中出现的次数,然后根据数字在arr2中出现与否来改动arr1,使得在arr2中有的数字在arr1中能按照他们的相对顺序重新排列;再次扫描bucket,把arr1中有但是arr2中没有的元素添加到arr1的末端。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] relativeSortArray(int[] arr1, int[] arr2) {
 3         int[] count = new int[1001];
 4         for (int n : arr1) {
 5             count[n]++;
 6         }
 7         int i = 0;
 8         for (int n : arr2) {
 9             while (count[n]-- > 0) {
10                 arr1[i++] = n;
11             }
12         }
13         for (int n = 0; n < count.length; n++) {
14             while (count[n]-- > 0) {
15                 arr1[i++] = n;
16             }
17         }
18         return arr1;
19     }
20 }

JavaScript实现

 1 /**
 2  * @param {number[]} arr1
 3  * @param {number[]} arr2
 4  * @return {number[]}
 5  */
 6 var relativeSortArray = function (arr1, arr2) {
 7     let bucket = {};
 8     let res = [];
 9     for (let i = 0; i < arr1.length; i++) {
10         if (bucket[arr1[i]]) {
11             bucket[arr1[i]]++;
12         } else {
13             bucket[arr1[i]] = 1;
14         }
15     }
16     for (let j = 0; j < arr2.length; j++) {
17         while (bucket[arr2[j]]) {
18             res.push(arr2[j]);
19             bucket[arr2[j]]--;
20         }
21     }
22     for (let key in bucket) {
23         while (bucket[key]) {
24             res.push(key);
25             bucket[key]--;
26         }
27     }
28     return res;
29 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12462225.html