LeetCode——1122. Relative Sorting of Arrays

Title description:

Give you two arrays, arr1 and arr2, the elements in arr2 are different, each element in arr2 appears in arr1, sort the elements in arr1 so that the relative order of the items in arr1 is relative to that in arr2 The order is the same. Elements that have not appeared in arr2 need to be placed at the end of arr1 in ascending order.

prompt:

  • 1 <= arr1.length, arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • The elements in arr2 arr2[i] are different
  • Every element arr2[i] in arr2 appears in arr1

Example:

  • 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]

code show as below:

class Solution {
    
    
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
    
    
        int n = arr1.length;
        int m = arr2.length;
        Map<Integer, Integer> map = new TreeMap<>();
        for (int j : arr1) {
    
    
            map.put(j, map.getOrDefault(j, 0) + 1);
        }
        int[] arr3 = new int[n];
        int k = 0;
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < map.get(arr2[i]); j++) {
    
    
                arr3[k] = arr2[i];
                k++;
            }
            map.remove(arr2[i]);
        }
        for (var entry : map.entrySet()) {
    
    
            for (int i = 0; i < entry.getValue(); i++) {
    
    
               arr3[k]=entry.getKey();
               k++;
            }
        }
        return arr3;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114269644