[코테 풀이] Queries on a Permutation With Key

시내·2024년 6월 27일

Q_1409) Queries on a Permutation With Key

출처 : https://leetcode.com/problems/queries-on-a-permutation-with-key/

Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:

  • In the beginning, you have the permutation P=[1,2,3,...,m].

  • For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].

Return an array containing the result for the given queries.

class Solution {
    public int[] processQueries(int[] queries, int m) {
        int[] answer = new int[queries.length];
        int ind = 0;
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int a = 1; a <= m; a++) {
            arrayList.add(a);
        }
        for (int i = 0; i < queries.length; i++) {
            for (int j = 0; j <= arrayList.size(); j++) {
                if (arrayList.get(j) == queries[i]) {
                    arrayList.remove(j);
                    arrayList.add(0, queries[i]);
                    answer[ind++] = j;
                    break;
                }
            }
        }
        return answer;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글