[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
class Solution {
public int[] solution(String[] keyinput, int[] board) {
int x = 0, y = 0;
int maxx = board[0] / 2, maxy = board[1] / 2;
for (String s : keyinput) {
if (s.equals("up")) {
y = Math.min(y + 1, maxy);
} else if (s.equals("down")) {
y = Math.max(y - 1, -maxy);
} else if (s.equals("left")) {
x = Math.max(x - 1, -maxx);
} else {
x = Math.min(x + 1, maxx);
}
}
return new int[]{x, y};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<string> keyinput, vector<int> board) {
int x = 0, y = 0;
int maxx = board[0] / 2, maxy = board[1] / 2;
for (string& s : keyinput) {
if (s == "up") {
y = min(y + 1, maxy);
} else if (s == "down") {
y = max(y - 1, -maxy);
} else if (s == "left") {
x = max(x - 1, -maxx);
} else {
x = min(x + 1, maxx);
}
}
return {x, y};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(keyinput, board):
x, y = 0, 0
maxx, maxy = board[0] // 2, board[1] // 2
for s in keyinput:
if s == "up":
y = min(y + 1, maxy)
elif s == "down":
y = max(y - 1, -maxy)
elif s == "left":
x = max(x - 1, -maxx)
else:
x = min(x + 1, maxx)
return [x, y]
This post is licensed under CC BY 4.0 by the author.