-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelativeSortArray.java
More file actions
24 lines (22 loc) · 833 Bytes
/
RelativeSortArray.java
File metadata and controls
24 lines (22 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package leetcode.array;
import java.util.*;
/**
* @ClassName RelativeSortArray
* @Description 数组的相对排序 https://leetcode-cn.com/problems/relative-sort-array/
* @Author changxuan
* @Date 2020/11/14 下午11:20
**/
public class RelativeSortArray {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
for(int num : arr1) list.add(num);
for(int i = 0; i < arr2.length; i++) map.put(arr2[i], i);
Collections.sort(list, (x, y) -> {
if(map.containsKey(x) || map.containsKey(y)) return map.getOrDefault(x, 1001) - map.getOrDefault(y, 1001);
return x - y;
});
for(int i = 0; i < arr1.length; i++) arr1[i] = list.get(i);
return arr1;
}
}