leetcode【贪心算法】这里用到了java8的API(真的简便

在这里插入图片描述
在这里插入图片描述

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中的一个元素(单个是一维数组)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值