# 数组的相对排序(1122)

# 题目

给你两个数组,arr1 和 arr2,

arr2 中的元素各不相同 arr2 中的每个元素都出现在 arr1 中 对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。

# 示例

输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] 输出:[2,2,2,1,4,3,3,9,6,7,19]

# 提示

  • 1 <= arr1.length, arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • arr2 中的元素 arr2[i] 各不相同
  • arr2 中的每个元素 arr2[i] 都出现在 arr1 中

# 算法

# 计数排序

  • 先遍历arr1将对应的数字出现次数保存在数组countingArr
  • 遍历arr2中的数字,将对应位置的数字按出现次数推入结果数组res,并将数字对应位置的出现次数countingArr[arr2[i]]设为0
  • 结束遍历后countingArr中只剩下arr2中没有出现过的数字和次数信息了
  • 遍历countingArr,按出现次数将数字推入结果数组
  • 返回结果数组res
export const relativeSortArray = (arr1, arr2) => {
	const countingArr = [];
	arr1.forEach((item) => (countingArr[item] = countingArr[item] ? countingArr[item] + 1 : 1));
	const res = [];
	arr2.forEach((item) => {
		countingArr[item] ? res.push(...new Array(countingArr[item]).fill(item)) : null;
		countingArr[item] = 0;
	});
	countingArr.forEach((item, index) => (item ? res.push(...new Array(item).fill(index)) : null));
	return res;
};
1
2
3
4
5
6
7
8
9
10
11