On an infinite plane, a robot initially stands at (0, 0)
and faces north. The robot can receive one of three instructions:
"G"
: go straight 1 unit;"L"
: turn 90 degrees to the left;"R"
: turn 90 degress to the right.
The robot performs the instructions
given in order, and repeats them forever.
Return true
if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Example 2:
Input: "GG" Output: false Explanation: The robot moves north indefinetely.
Example 3:
Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Note:
1 <= instructions.length <= 100
instructions[i]
is in{'G', 'L', 'R'}
第一次參加競賽。 2019/05/11 10:30pm 有點意思
新題果然都是看起來很難的
一共四道題,只做出來一道easy, 排名1790/4109, 提交了3次錯誤答案。
丟人啊哈哈哈,那道題就不粘出來了。第二道題提交了1次,錯了。
後來過了時間,改對了
代碼寫的是真的難看
題目真的不難,思路完全有,並且沒什麼問題。
只是數組多了就亂了,不簡潔,寫起來小錯誤就會更多,變量名隨便亂起,自己都不知道該用什麼。
數組下標從0開始,與題目裏面設計的index對應不上,想不清楚什麼時候該減1,什麼時候不動。
自己跑test case能力很弱,test case設計不好,corner case考慮不到,這些都是問題。
總體上說,思路不夠清晰。其實這兩道題都很簡單,都應該是一次A過 bug free的那一種。
看來改變coding的習慣還是要時刻注意。加油~!希望下週至少能順利A出來兩道題吧。
class Solution {
public int[] gardenNoAdj(int N, int[][] paths) {
int[] res = new int[N];
if (paths == null || paths.length == 0 || paths[0].length == 0){
for(int i = 0; i < N; i++){
res[i] = 1;
}
return res;
}
Map<Integer, int[]> map = new HashMap<>();
for(int[] path: paths){
int min = Math.min(path[0], path[1]);
int max = Math.max(path[0], path[1]);
if (map.containsKey(max)){
int[] tmp = map.get(max);
if (tmp[1] == -1) tmp[1] = min;
else tmp[2] = min;
map.put(max, tmp);
}
else{
int[] tmp = new int[3];
tmp[0] = min;
tmp[1] = -1;
tmp[2] = -1;
map.put(max, tmp);
}
}
res[0] = 1;
for(int i = 1; i < N; i++){
if (!map.containsKey(i+1))
res[i] = 1;
else{
int[] tmp = map.get(i+1);
int[] tmp2 = new int[4];
for(int k = 0; k < 4; k++)
tmp2[k] = 0;
if (tmp[0] != -1) tmp2[res[tmp[0] - 1]-1] = 1;
if (tmp[1] != -1) tmp2[res[tmp[1] - 1]-1] = 1;
if (tmp[2] != -1) tmp2[res[tmp[2] - 1]-1] = 1;
if (tmp2[0] == 0) res[i] = 1;
else if (tmp2[1] == 0) res[i] = 2;
else if (tmp2[2] == 0) res[i] = 3;
else res[i] = 4;
}
}
return res;
}
}