索引越界问题 - LeetCode322

class Solution {
    //利用bfs来进行遍历
    public int coinChange(int[] coins, int amount) {
        Deque<int[] > queue = new LinkedList();
        boolean[] vst = new boolean[amount + 1];
        //初始化
        vst[0] = true;
        queue.addLast(new int[]{0,0}); // {a,b} a已凑金额,b当前步长
        while(!queue.isEmpty()){
            int[] arr = queue.pollFirst();
            int node = arr[0], w = arr[1];
            if(node == amount) return w;
            for(int coin : coins){
                //代码出错的地方
                if((coin + node)  > amount || vst[coin + node]) continue;
                queue.addLast(new int[]{coin + node, w + 1});
                vst[coin + node] = true;
            }
        }
        return -1;
    }
}

  如果代码修改

if(coin > amount - node || vst[coin + node]) continue;

就会导致在特殊的情况下出现索引越界,这种特殊情况是由于int的最大值限制导致的

node为1时,coin为2147483647(即int的最大值),此时再加1,就会等于-2147483648,就会前面的判断错误,也会导致后面的数组索引越界。

所以之后在写判断时,能减则不加!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值