[코테 풀이] Relative Sort Array

시내·2024년 6월 29일

Q_1122) Relative Sort Array

출처 : https://leetcode.com/problems/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.

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] answer = new int[arr1.length];
        int ind = 0;
        ArrayList<Integer> one = new ArrayList<>(), two = new ArrayList<>(), notContain = new ArrayList<>();
        for (int a : arr1) one.add(a);
        for (int b : arr2) two.add(b);
        for (int i = 0; i < arr1.length; i++) {
            if (!two.contains(arr1[i])) notContain.add(arr1[i]);
        }
        Collections.sort(notContain);
        
        for (int j = 0; j < arr2.length; j++) {
            for (int k = 0; k < count(arr2[j], arr1); k++) {
                answer[ind++] = arr2[j];
            }
        }
        for(int q = 0; q <notContain.size(); q++){
            answer[ind++] = notContain.get(q);
        }
        return answer;
    }
    
     public int count(int a, int[] nums) {
        int counts = 0;
        for (int n : nums) {
            if (n == a) counts++;
        }
        return counts;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글