๋ฌธ์
ํ์ด1
import java.util.*;
class Solution {
public int[] solution(int[] emergency) {
int[] answer = new int[emergency.length];
int[] copied = emergency.clone();
Arrays.sort(copied);
for(int i = 0; i < emergency.length; i++) {
for(int j = 0; j < copied.length; j++) {
if(emergency[i] == copied[j]) answer[i] = emergency.length - j;
}
}
return answer;
}
}
ํ์ด2
์ฒ์์ ํผ ์ด์ค for๋ฌธ๋ณด๋ค HashMap์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋๊ฒ ๋ ํจ์จ์ ์ ๋๋ค. ์ด์ค for๋ฌธ์ ์ฌ์ฉํ๋ฉด ์๊ฐ ๋ณต์ก๋๊ฐ ์ต๋ O(N^2)๊ฐ ๋๋๋ฐ, HashMap์ ์ฌ์ฉํ ๊ฒฝ์ฐ O(NlogN) ๋๋ O(N)๊น์ง ๊ฐ์ ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ๋๋ค.
import java.util.*;
class Solution {
public int[] solution(int[] emergency) {
int[] answer = new int[emergency.length];
int rank = 1;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < emergency.length; i++) {
map.put(emergency[i], i);
}
int[] copied = emergency.clone();
Arrays.sort(copied);
for(int i = copied.length - 1; i >= 0; i--) {
int idx = map.get(copied[i]);
answer[idx] = rank;
rank++;
}
return answer;
}
}
'๐ Coding Test > Programmers Lv0' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค Lv0] ์จ์ด์๋ ์ซ์์ ๋ง์ (2) | ์๋ฐ (0) | 2024.12.18 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค Lv0] ์๋ผ์ ๋ฐฐ์ด๋ก ์ ์ฅํ๊ธฐ | ์๋ฐ (1) | 2024.11.09 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv0] n ๋ฒ์งธ ์์๋ถํฐ | ์๋ฐ (0) | 2024.10.24 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv0] ๋ฐฐ์ด ์กฐ๊ฐํ๊ธฐ | ์๋ฐ (0) | 2024.10.24 |