数组: 数组相对排序
给定两个数组,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 中
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); int[] arr1 = new int[]{1, 3, 2, 8, 10, 4, 6, 19, 9, 11, 7}; int[] arr2 = new int[]{2, 1, 4, 3, 9, 6}; System.out.println(Arrays.stream(solution.relativeSortArray(arr1, arr2)).boxed().collect(Collectors.toList())); } public int[] relativeSortArray(int[] arr1, int[] arr2) { int left = 0;//需要替换的索引 int right;//arr1需要判断的索引 int swap;//交换的值 for (int i = 0; i < arr2.length; i++) { right = 0; while (right < arr1.length) { if (arr1[right] == arr2[i]) {//相等 swap = arr1[left]; arr1[left] = arr1[right]; arr1[right] = swap; left++; } right++; } } for (int i = left; i < arr1.length-1; i++) { left = i;//前面已经根据arr2排序完了,根据升序排序剩余的 right = i+1; while (right < arr1.length){ if(arr1[right]<arr1[left]){ swap = arr1[left]; arr1[left]=arr1[right]; arr1[right] = swap; } right++; } } return arr1; } }
//计数排序
public int[] relativeSortArray(int[] arr1, int[] arr2) {
int max = 0;
for (int i : arr1) {//求最大值初始化max + 1大小的int数组
max = Math.max(max, i);
}
int[] counts = new int[max + 1];
for (int i : arr1) {//统计arr1中各个值出现的次数,元素值是索引
counts[i]++;
}
for (int i = 0; i < arr1.length; i++) {//讲arr1元素设置为0 也可以new int[]
arr1[i] = 0;
}
int index = 0;//给arr1中赋值的索引
for (int i : arr2) {
for (int j = 0; j < counts[i]; j++) {//先对arr1设置arr2中元素的值,顺序按arr2中元素的舒徐
arr1[index++] = i;
}
counts[i] = 0;
}
for (int i = 0; i < max + 1; i++) {
for (int j = 0; j < counts[i]; j++) {
arr1[index++] = i;
}
}
return arr1;
}
题目出自LeetCode