[Programmers] #120861 - 캐릭터의 좌표 [Java][C++][Python]
[Programmers] #120861 - 캐릭터의 좌표 [Java][C++][Python]
1. 아이디어
주어진 문자열 keyinput을 순서대로 훑으며 현재 좌표를 갱신하면 되는 간단한 문제다. board의 두 변이 모두 홀수라 중앙 $(0, 0)$에서 각 축으로 갈 수 있는 최대 칸 수는 변 길이의 절반이고, 매 이동마다 좌표를 이 범위로 자르면 판을 벗어나는 입력은 자연히 무시된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = keyinput의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[] solution(String[] keyinput, int[] board) {
int[] pos = {0, 0};
int maxx = board[0] / 2;
int maxy = board[1] / 2;
for (String s : keyinput) {
if (s.equals("up")) {
pos[1] = Math.min(pos[1] + 1, maxy);
} else if (s.equals("down")) {
pos[1] = Math.max(pos[1] - 1, -maxy);
} else if (s.equals("left")) {
pos[0] = Math.max(pos[0] - 1, -maxx);
} else {
pos[0] = Math.min(pos[0] + 1, maxx);
}
}
return pos;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<string> keyinput, vector<int> board) {
vector<int> pos(2);
int maxx = board[0] / 2;
int maxy = board[1] / 2;
for (string& s : keyinput) {
if (s == "up") {
pos[1] = min(pos[1] + 1, maxy);
} else if (s == "down") {
pos[1] = max(pos[1] - 1, -maxy);
} else if (s == "left") {
pos[0] = max(pos[0] - 1, -maxx);
} else {
pos[0] = min(pos[0] + 1, maxx);
}
}
return pos;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(keyinput, board):
pos = [0, 0]
maxx, maxy = board[0] // 2, board[1] // 2
for key in keyinput:
if key == "up":
pos[1] = min(pos[1] + 1, maxy)
elif key == "down":
pos[1] = max(pos[1] - 1, -maxy)
elif key == "left":
pos[0] = max(pos[0] - 1, -maxx)
else:
pos[0] = min(pos[0] + 1, maxx)
return pos
This post is licensed under CC BY 4.0 by the author.