题目来源:
leetcode题目,网址:LCR 075. 数组的相对排序 - 力扣(LeetCode)
解题思路:
先将 arr1 中在 arr2 中出现过的元素按顺序排序,然后将剩余元素按升序排序。
解题代码:
- class Solution {
- public int[] relativeSortArray(int[] arr1, int[] arr2) {
- int thisPos=0;
- for(int j=0;j<arr2.length;j++){//i 指向arr1,j指向 arr2
- for(int k=thisPos;k<arr1.length;k++){
- if(arr1[k]==arr2[j]){
- arr1[k]=arr1[thisPos];
- arr1[thisPos]=arr2[j];
- thisPos++;
- }
- }
- }
- for(int i=thisPos;i<arr1.length;i++){
- for(int j=arr1.length-1;j>i;j--){
- if(arr1[j]<arr1[j-1]){
- int temp=arr1[j];
- arr1[j]=arr1[j-1];
- arr1[j-1]=temp;
- }
- }
- }
- return arr1;
- }
- }
总结:
官方题解给出了两种解法。第一种是重写比较器自定义排序。第二种是计数排序。