每日一题:335. 路径交叉

解题思路

找到所有会重复的情况即可

代码

//最终解法
class Solution {
    public boolean isSelfCrossing(int[] distance) {
        for(int i=3, l=distance.length; i<l; i++) {
            // Case 1: current line crosses the line 3 steps ahead of it
            if(distance[i]>=distance[i-2] && distance[i-1]<=distance[i-3]) {
                return true;
            }
                // Case 2: current line crosses the line 4 steps ahead of it
            else if(i>=4 && distance[i-1]==distance[i-3] && distance[i]+distance[i-4]>=distance[i-2]) {
                return true;
            }
                // Case 3: current line crosses the line 6 steps ahead of it
            else if(i>=5 && distance[i-2]>=distance[i-4] && distance[i]+distance[i-4]>=distance[i-2] && distance[i-1]<=distance[i-3] && distance[i-1]+distance[i-5]>=distance[i-3]) {
                return true;
            }
        }
        return false;
    }
}

//记录每次经过的点,如果重复就说明有相交路线,但是时间复杂度高会超时
public boolean isSelfCrossing(int[] distance) {
        /*
        先向北移动 distance[0] 米,然后向西移动 distance[1] 米,向南移动 distance[2] 米,向东移动 distance[3] 米
        即上 左 下 右 四方向
         */
        Map<Integer, HashSet<Integer>> map = new HashMap<>();
        int[][] dir = new int[][]{{0,1},{-1,0},{0,-1},{1,0}};
        int x=0,y=0;
        HashSet<Integer> set = new HashSet<>();
        set.add(y);
        map.put(x,set);
        for (int i=0;i<distance.length;i++){
            for (int j=0;j<distance[i];j++){
                x += dir[i][0];
                y += dir[i][1];
                if (!map.containsKey(x)){
                    HashSet<Integer> hashSet = new HashSet<>();
                    hashSet.add(y);
                    map.put(x,hashSet);
                }else {
                    HashSet<Integer> hashSet = map.get(x);
                    if (hashSet.contains(y)){
                        return true;
                    }
                    hashSet.add(y);
                }
            }
        }
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值