LeetCode 1122. Relative Sort Array
考点 | 难度 |
---|---|
Sorting | Easy |
题目
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 do not appear in arr2
should be placed at the end of arr1
in ascending order.
思路
把所有arr2
中的数字存到map里。对于arr1
里的每个数,如果在arr2
中出现过就更新map,如果没出现过,加到result的结尾。根据arr2
的顺序,按照每个数字出现的次数把result的第一部分填满。sort result的后半部分。
答案
public int[] relativeSortArray(int[] arr1, int[] arr2) {
//create map for counting numbers in arr2. Initialize everything with zeroes
Map<Integer, Integer> m = new HashMap();
for (int num : arr2) {
m.put(num, 0);
}
int last = arr1.length - 1;
int[] res = new int[arr1.length];
//iterate over arr1 and count numbers of time this element is in arr1
for (int num : arr1) {
//if number is from arr2 - increment count
if (m.containsKey(num))
m.put(num, m.get(num) + 1);
//otherwise add element to the end of res and decrement the pointer
else {
res[last--] = num;
}
}
//iterate over arr2, fill elements in res based on it's count
int p = 0;
for (int num : arr2) {
int c = m.get(num);
for (int i = 0; i < c; i++) {
res[p++] = num;
}
}
//now sort the leftovers - p points to the first element in series of those from arr2 that are not in arr1
Arrays.sort(res, p, res.length);
return res;
}