LeetCode——1652.拆炸弹

通过万岁!!!

  • 题目:给你一个数组,和一个数k,然后数组的每个位置要变成接下来k个数的和。如果k是小于0的则是前k个。
  • 思路一:两层for循环,并且要判断k的正负。时间复杂度是n*k。
  • 思路二:用滑动窗口来保存这个k个数的和,然后每次加一个,减去一个即可。
  • 技巧:数组遍历、滑动窗口

java代码——思路一

class Solution {
    public int[] decrypt(int[] code, int k) {
        int len = code.length;
        int[] res = new int[len];
        if (k == 0) {
            return res;
        }
        boolean flag = false;
        if (k < 0) {
            flag = true;
            k = -k;
        }
        int temp;
        for (int i = 0; i < len; i++) {
            temp = 0;
            for (int j = 1; j <= k; j++) {
                temp += code[(i + (flag ? -j : j) + len) % len];
            }
            res[i] = temp;
        }
        return res;
    }
}

java代码——思路二

class Solution {
    public int[] decrypt(int[] code, int k) {
        int len = code.length;
        int[] res = new int[len];
        if (k == 0) {
            return res;
        }
        int temp = 0;
        if (k > 0) {
            for (int i = 1; i <= k; i++) {
                temp += code[i];
            }
            for (int i = 0; i < len; i++) {
                res[i] = temp;
                temp -= code[(i + 1) % len];
                temp += code[(i + 1 + k) % len];
            }
        } else {
            for (int i = len + k; i < len; i++) {
                temp += code[i];
            }
            for (int i = 0; i < len; i++) {
                res[i] = temp;
                temp -= code[(i + k + len) % len];
                temp += code[i % len];
            }
        }
        return res;
    }
}
  • 总结:题目不是特别难,第一种方法是比较笨的方法,但是里面我运用了三目运算符,也算是对代码进行了简化。第二种方法是比较好的方法。两种方法都需要申请一个额外的数组,这个是不太好的,但是没有想到好一点的方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值