Development/CodingTest
[ํ๋ก๊ทธ๋๋จธ์ค] Java ๋ค๋ฆฌ๋ฅผ ์ง๋๋ ํธ๋ญ
Kirok Kim
2021. 12. 14. 22:12
- ๊ธฐ์กด์๋ queue๋ฅผ array๋ฆฌ์คํธ๋ก ์ด๋ป๊ฒ๋ ํ์๋๋ฐ ๊ทธ๊ฑธ ์ฐ์ง ์๊ณ ์๋ ๋๋ฌด ๋ณต์กํ๊ฒ ์ฝ๋๊ฐ ์ง์ฌ์ ธ์ ์๊ฐ์ด ๋ง์ด ๊ฑธ๋ ธ๋ค.
์๋๋ queue๋ฅผ ์ด์ฉํ ํด๋ต์ด๋ค.
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;
public class Truck {
int w;
int d;
public Truck(int w, int d) {
this.w = w;
this.d = d;
}
}
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int wL = weight;
int cnt = 0;
Truck t = null;
Queue<Truck> o = new LinkedList<Truck>();
List<Truck> i = new ArrayList<Truck>();
for (int l : truck_weights) {
o.add(new Truck(l, bridge_length));
}
while (!(i.isEmpty()&&o.isEmpty())) {
cnt++;
if (!i.isEmpty() && i.get(0).d <= 0) {
wL += i.get(0).w;
i.remove(0);
}
if (!o.isEmpty() && wL - o.peek().w >= 0) {
wL -= o.peek().w;
i.add(o.poll());
}
for (int j = 0; j < i.size(); j++) {
t = i.get(j);
t.d--;
}
}
return cnt;
}
}
for (int l : truck_weights) {
o.add(new Truck(l, bridge_length));
}
- ํธ๋ญ์ ์ ๋ถ o์๋ค๊ฐ ์ ์ฅ์ ํด์ค๋ค.
- ์ด๋ ํธ๋ญ์ ํธ๋ญ์ ๋ฌด๊ฒ, ๋ค๋ฆฌ์ ๊ธธ์ด์ ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ์ง๋ค.
while (!(i.isEmpty()&&o.isEmpty())) {
cnt++;
- ๋ค๋ฆฌ ์ ํธ๋ญ(i)์ ๊ฑด๋๊ธฐ ์ ํธ๋ญ(o)๊ฐ ์ ๋ถ ๋น ๋๊น์ง ๊ณ์ ์คํ์ ํ๊ณ ๋ค๋ฆฌ๋ฅผ ์ ๋ถ ๊ฑด๋ ๋์ ์๊ฐ์ ์ธก์ ํ๊ธฐ ์ํด cnt++ํด์ค๋ค.
if (!i.isEmpty() && i.get(0).d <= 0) {
wL += i.get(0).w;
i.remove(0);
}
- ๋ค๋ฆฌ ์์ ํธ๋ญ์ด ์๊ณ ๋ค๋ฆฌ ์์ ์ฒซ ๋ฒ์งธ ํธ๋ญ์ ๋จ์ ๊ฑฐ๋ฆฌ๊ฐ 0์ดํ ์ผ ๋
- ๋ค๋ฆฌ๊ฐ ๊ฒฌ๋ ์ ์๋ ํ์ค(wL)์ ์ฒซ ๋ฒ์งธ ํธ๋ญ์ ๋ฌด๊ฒ๋งํผ ๋ํด์ฃผ๊ณ ๋ค๋ฆฌ ์ ์ฒซ ๋ฒ์งธ ํธ๋ญ์ ์ ๊ฑฐํด์ค๋ค.
if (!o.isEmpty() && wL - o.peek().w >= 0) {
wL -= o.peek().w;
i.add(o.poll());
}
- ๊ฑด๋๊ธฐ ์ ํธ๋ญ(o)์ด ์์ง ์๊ณ ๊ฒฌ๋ ์ ์๋ ํ์ค(wL)์ด ๊ฑด๋๋ ค๋ ํธ๋ญ์ ๋ฌด๊ฒ๋ฅผ ๋ ๊ฒฌ๋ ์ ์์ผ๋ฉด ๊ฒฌ๋ ์ ์๋ ๋ฌด๊ฒ์ ๊ฑด๋๋ ์ฒซ ํธ๋ญ์ ๋ฌด๊ฒ ๋งํผ ๋นผ์ฃผ๊ณ ๊ทธ ํธ๋ญ์ ๋ค๋ฆฌ ์์ ์๋ ํธ๋ญ(i)์์ ๋บด์ค๋ค.
for (int j = 0; j < i.size(); j++) {
t = i.get(j);
t.d--;
}
}
return cnt;
}
}
- ๋ค๋ฆฌ ์์ ์๋ ํธ๋ญ์ ๋จ์์๋ ๊ฑฐ๋ฆฌ๋ฅผ ์๊ฐ์ด ๊ฐ๋ฉด ๊ฐ์๋ก ํ๋์ฉ ์ค์ฌ์ค๋ค. ๋ง์ง๋ง ๋ฆฌํด ๊ฐ์ ๋ค ๊ฑด๋ ์๊ฐ์ธ cnt๊ฐ ๋ฐํ์ด ๋๋ค.
- ๋ณดํต์ getter setter๋ก ํ์ง๋ง truckํด๋์ค์ ํ๋์ ์ ๊ทผ์ ํ์๋ฅผ public์ด๋ผ๊ณ ์ง์ ํด์คฌ๊ณ getter,setter๋ฅผ ๋ฐ๋ก ๋ง๋ค์ง ์์๊ธฐ ๋๋ฌธ์ ์ง์ ๋จ์์๋ ๊ฑฐ๋ฆฌ๋ฅผ ๋ฐ๊พธ์ด์ฃผ์๋ค.
๋ฐ์ํ