给定两个数组,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; } }
题目出自LeetCode
标签:right,数组,int,++,arr2,arr1,left From: https://www.cnblogs.com/itzkd/p/16769512.html