LeetCode 周赛上分之旅 #44 同余前缀和问题与经典倍增

2023-09-05  本文已影响0人  彭旭锐

T1. 统计对称整数的数目(Easy)

T2. 生成特殊数字的最少操作(Medium)

T3. 统计趣味子数组的数目(Medium)

T4. 边权重均等查询(Hard)


T1. 统计对称整数的数目(Easy)

https://leetcode.cn/problems/count-symmetric-integers/

题解(模拟)

根据题意模拟,亦可以使用前缀和预处理优化。

class Solution {
    fun countSymmetricIntegers(low: Int, high: Int): Int {
        var ret = 0
        for (x in low..high) {
            val s = "$x"
            val n = s.length
            if (n % 2 != 0) continue
            var diff = 0
            for (i in 0 until n / 2) {
                diff += s[i] - '0'
                diff -= s[n - 1 - i] - '0'
            }
            if (diff == 0) ret += 1
        }
        return ret
    }
}

复杂度分析:


T2. 生成特殊数字的最少操作(Easy)

https://leetcode.cn/problems/minimum-operations-to-make-a-special-number/

题解一(回溯)

思维题,这道卡了多少人。

可以用回溯解决:

class Solution {
    fun minimumOperations(num: String): Int {
        val memo = HashMap<String, Int>()

        fun count(x: String): Int {
            val n = x.length
            if (n == 1) return if (x == "0") 0 else 1
            if (((x[n - 2] - '0') * 10 + (x[n - 1]- '0')) % 25 == 0) return 0
            if(memo.containsKey(x))return memo[x]!!
            val builder1 = StringBuilder(x)
            builder1.deleteCharAt(n - 1)
            val builder2 = StringBuilder(x)
            builder2.deleteCharAt(n - 2)
            val ret = 1 + min(count(builder1.toString()), count(builder2.toString()))
            memo[x]=ret
            return ret
        }
        
        return count(num)
    }
}

复杂度分析:

题解二(双指针)

初步分析:

具体实现:

class Solution {
    fun minimumOperations(num: String): Int {
        val n = num.length
        var ret = n
        for (choice in arrayOf("00", "25", "50", "75")) {
            // 双指针
            var j = 1
            for (i in n - 1 downTo 0) {
                if (choice[j] != num[i]) continue
                if (--j == -1) {
                    ret = min(ret, n - i - 2)
                    break
                }
            }
        }
        // 特殊情况
        ret = min(ret, n - num.count { it == '0'})
        return ret
    }
}

复杂度分析:


T3. 统计趣味子数组的数目(Medium)

https://leetcode.cn/problems/count-of-interesting-subarrays/

题解(同余 + 前缀和 + 散列表)

初步分析:

分析到这里,容易想到用前缀和实现:

组合以上技巧:

class Solution {
    fun countInterestingSubarrays(nums: List<Int>, m: Int, k: Int): Long {
        val n = nums.size
        var ret = 0L
        val preSum = HashMap<Int, Int>()
        preSum[0] = 1 // 注意空数组的状态
        var cur = 0
        for (i in 0 until n) {
            if (nums[i] % m == k) cur ++ // 更新前缀和
            val key = cur % m
            val target = (key - k + m) % m
            ret += preSum.getOrDefault(target, 0) // 记录方案
            preSum[key] = preSum.getOrDefault(key, 0) + 1 // 记录前缀和
        }
        return ret
    }
}

复杂度分析:

相似题目:


T4. 边权重均等查询(Hard)

https://leetcode.cn/problems/minimum-edge-weight-equilibrium-queries-in-a-tree/

题解(倍增求 LCA、树上差分)

初步分析:

思考实现:

现在的关键问题是,如何快速地找到 <x, y> 的最近公共祖先 LCA?

对于单次 LCA 操作来说,我们可以走 DFS 实现 O(n) 时间复杂度的算法,而对于多次 LCA 操作可以使用 倍增算法 预处理以空间换时间,单次 LCA 操作的时间复杂度进位 O(lgn)

在 LeetCode 有倍增的模板题 1483. 树节点的第 K 个祖先

在求 LCA 时,我们先把 <x, y> 跳到相同高度,再利用倍增算法向上跳 2^j 个父节点,直到到达相同节点即为最近公共祖先。

class Solution {
    fun minOperationsQueries(n: Int, edges: Array<IntArray>, queries: Array<IntArray>): IntArray {
        val U = 26
        // 建图
        val graph = Array(n) { LinkedList<IntArray>() }
        for (edge in edges) {
            graph[edge[0]].add(intArrayOf(edge[1], edge[2] - 1))
            graph[edge[1]].add(intArrayOf(edge[0], edge[2] - 1))
        }

        // 预处理深度、倍增祖先节点、倍增路径信息
        val m = 32 - Integer.numberOfLeadingZeros(n - 1)
        val depth = IntArray(n)
        val parent = Array(n) { IntArray(m) { -1 }} // parent[i][j] 表示 i 的第 2^j 个父节点
        val cnt = Array(n) { Array(m) { IntArray(U) }} // cnt[i][j] 表示 <i - 2^j> 个父节点的路径信息
        
        fun dfs(i: Int, par: Int) {
            for ((to, w) in graph[i]) {
                if (to == par) continue // 避免回环
                depth[to] = depth[i] + 1
                parent[to][0] = i
                cnt[to][0][w] = 1
                dfs(to, i)
            }
        }

        dfs(0, -1) // 选择 0 作为根节点

        // 预处理倍增
        for (j in 1 until m) {
            for (i in 0 until n) {
                val from = parent[i][j - 1]
                if (-1 != from) {
                    parent[i][j] = parent[from][j - 1]
                    cnt[i][j] = cnt[i][j - 1].zip(cnt[from][j - 1]) { e1, e2 -> e1 + e2 }.toIntArray()
                }
            }
        }

        // 查询
        val q = queries.size
        val ret = IntArray(q)
        for ((i, query) in queries.withIndex()) {
            var (x, y) = query
            // 特判
            if (x == y || parent[x][0] == y || parent[y][0] == x) {
                ret[i] = 0
            }
            val w = IntArray(U) // 记录路径信息
            var path = depth[x] + depth[y] // 记录路径长度
            // 先跳到相同高度
            if (depth[y] > depth[x]) {
                val temp = x
                x = y
                y = temp
            }
            var k = depth[x] - depth[y]
            while (k > 0) {
                val j = Integer.numberOfTrailingZeros(k) // 二进制分解
                w.indices.forEach { w[it] += cnt[x][j][it] } // 记录路径信息
                x = parent[x][j] // 向上跳 2^j 个父节点
                k = k and (k - 1)
            }

            // 再使用倍增找 LCA
            if (x != y) {
                for (j in m - 1 downTo 0) { // 最多跳 m - 1 次
                    if (parent[x][j] == parent[y][j]) continue // 跳上去相同就不跳
                    w.indices.forEach { w[it] += cnt[x][j][it] } // 记录路径信息
                    w.indices.forEach { w[it] += cnt[y][j][it] } // 记录路径信息
                    x = parent[x][j]
                    y = parent[y][j] // 向上跳 2^j 个父节点
                }
                // 最后再跳一次就是 lca
                w.indices.forEach { w[it] += cnt[x][0][it] } // 记录路径信息
                w.indices.forEach { w[it] += cnt[y][0][it] } // 记录路径信息
                x = parent[x][0]
            }
            // 减去重链长度
            ret[i] = path - 2 * depth[x] - w.max()
        }
        return ret
    }
}

复杂度分析:


上一篇 下一篇

猜你喜欢

热点阅读