class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
// 北 东 南 西
// 0 1 2 3
//-2 i+3
//-1 i+1
//set去重
Set<String> obs = Arrays.stream(obstacles).map(a -> a[0] + " " + a[1]).collect(Collectors.toSet());//2.障碍物编码存入set
int x = 0, y = 0, i= 0, res = 0;//定义坐标 方向
for (int command : commands) { //3.遍历命令
if (command == -1) {
i = (i + 1) % 4;
}else if (command == -2){
i = (i + 3) % 4;
}else while (command-- > 0 && !obs.contains((x + dx[i]) + " " + (y + dy[i]))) {
//不在障碍物这里
x += dx[i];
y += dy[i];
res = Math.max(res, x * x + y * y);
}
}
return res;
}
}
这里用到了一些java8的APIjava8的 stream().map().collect()
讲解的很详细,有普通到这个api使用的过程
Set<String> obs = Arrays.stream(obstacles).map(a -> a[0] + " " + a[1]).collect(Collectors.toSet());//2.障碍物编码存入set
这里的a代指,obstacles中的一个元素(单个是一维数组)