算法: 获取两个数组的公共数字1122. Relative Sort Array

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 获取两个数组的公共数字1122. Relative Sort Array相关的知识,希望对你有一定的参考价值。

1122. Relative Sort Array

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.

Example 1:

Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]

Example 2:

Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
Output: [22,28,8,6,17,44]

Constraints:

  • 1 <= arr1.length, arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • All the elements of arr2 are distinct.
  • Each arr2[i] is in arr1.

利用数字范围[0, 1000]简化解法

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] cnt = new int[1001];
        int i = 0;
        for (int a1: arr1) cnt[a1]++;
        for (int a2: arr2) {
            while (cnt[a2]-- > 0) arr1[i++] = a2;
        }
        for (int k = 0; k < 1001; k++) {
            while (cnt[k]-- > 0) arr1[i++] = k;
        }
            
        return arr1;
    }
}

如果没有数字范围的约束

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int n : arr1) map.put(n, map.getOrDefault(n, 0) + 1);
        int i = 0;
        for(int n : arr2) {
            for(int j = 0; j < map.get(n); j++) {
                arr1[i++] = n;
            }
            map.remove(n);
        }
        for(int n : map.keySet()){
            for(int j = 0; j < map.get(n); j++) {
                arr1[i++] = n;
            }
        }
        return arr1;
    }
}

参考

https://leetcode.com/problems/relative-sort-array/discuss/335056/Java-in-place-solution-using-counting-sort

以上是关于算法: 获取两个数组的公共数字1122. Relative Sort Array的主要内容,如果未能解决你的问题,请参考以下文章

获取两个字符串全部公共的子串算法

如何比较两个对象数组并获取公共对象

基础算法基础算法转载

使用模数和公共指数的 C# RSA 加密

算法作业!!求两个不等长有序数组的中位数!

两个字符串查找最大公共子串