Leetcode 2100.适合劫银行的日子

链接: https://leetcode-cn.com/problems/find-good-days-to-rob-the-bank/

Leetcode 2100.适合劫银行的日子_第1张图片

 思路:

前缀和:
    g数组:表示下标i与i - 1 的大小关系
    规定:security[i] > security[i - 1] g[i] = 1;
        security[i] < security[i - 1] g[i] = -1;
        security[i] = security[i - 1] g[i] = 0;
    在 [i - time, i + time) 内满足:
        (i - time, i] 1的个数为0
        (i, i + time] -1的个数为0
    需要左开右闭区间,使用前缀和时,用i + 1位置记录i的状态;a[i]表示i 与 i - 1关系,但是此时i 和 i - 1的关系并不关心

 代码:

   public List goodDaysToRobBank(int[] security, int time) {
        if (security.length < 2 * time + 1) return new ArrayList<>();
        List res = new ArrayList<>();

        int len = security.length;
        int a[] = new int[len + 1];
        int b[] = new int[len + 1];
        int g[] = new int[len];
        for (int i = 1; i < len; i++) {
            if (security[i] == security[i - 1]) continue;
            g[i] = security[i] < security[i - 1] ? -1 : 1;
        }

        for (int i = 1; i <= len ;i++) a[i] = a[i - 1] + (g[i - 1] == 1 ? 1 : 0);
        for (int i = 1; i <= len ;i++) b[i] = b[i - 1] + (g[i - 1] == -1 ? 1 : 0);

        for (int i = time; i < len - time; i++) {
            if (a[i + 1] - a[i - time + 1] > 0) continue;
            if (b[i + 1 + time] - b[i + 1] > 0) continue;
            res.add(i);
        }
        return res;
    }

你可能感兴趣的:(leetcode,算法,职场和发展)