304. Range Sum Query 2D - Immutable

Problem


Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

Solution

和  Range Sum Query - Immutable 很像。
就是用一个二维数组,其中每个元素 dp[i][j] 表示以matrix[0][0]为左上角,matrix[i][j]以右下角组成的矩形中所有元素的和,
再用 arrSum[j] 表示该行从 0 到 j 所有元素的和,
这样 dp[i][j] = dp[i-1][j] + arrSum[j] 

class NumMatrix {
    vector<vector<int>> sumMatrix;
public:
    NumMatrix(vector<vector<int>> &matrix) {
        if(matrix.empty() || matrix[0].empty()) return;
        
        const int M = matrix.size(), N = matrix[0].size();
        sumMatrix.resize(M, vector<int>(N, 0));
        
        sumMatrix[0][0] = matrix[0][0];
        for( int j = 1; j < N; j++){
            sumMatrix[0][j] = sumMatrix[0][j-1] + matrix[0][j];
        }
        
        for( int i = 1; i < M ; i++){
            vector<int> sumArr(N, 0);
            sumArr[0] = matrix[i][0];
            for( int j = 0; j < N ; j++){
                if(j != 0) sumArr[j] = sumArr[j - 1] + matrix[i][j];
                sumMatrix[i][j] = sumMatrix[i-1][j] + sumArr[j];
            }
        }
    }
    
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        if(col1 == 0 && row1 == 0) return sumMatrix[row2][col2];
        if(col1 == 0) return sumMatrix[row2][col2] - sumMatrix[row1-1][col2];
        if(row1 == 0) return sumMatrix[row2][col2] - sumMatrix[row2][col1-1];
        
        return sumMatrix[row2][col2] - sumMatrix[row2][col1 -1] - sumMatrix[row1-1][col2] + sumMatrix[row1-1][col1-1];
    }
};



看了 这个答案之后 https://leetcode.com/course/chapters/leetcode-101/range-sum-query-2d-immutable/
发现我的 code 还可以简化很多,
 
dp的大小用  M + 1 行和 N + 1列来表示,其中左左边的一列和最上面的一行用零来表示 boarder,
这样  dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i-1][j-1] ,i 和 j分别都从1开始累加久好啦~~~~

这样在算 sumRegion时,也没有那么多 corner case 啦~~~~ 微笑 吐舌头 






【多种改进粒子群算法进行比较】基于启发式算法的深度神经网络卸载策略研究【边缘计算】(Matlab代码实现)内容概要:本文围绕“基于多种改进粒子群算法比较的深度神经网络卸载策略研究”展开,聚焦于边缘计算环境下的计算任务卸载优化问题。通过引入多种改进的粒子群优化(PSO)算法,并与其他启发式算法进行对比,旨在提升深度神经网络模型在资源受限边缘设备上的推理效率与系统性能。文中详细阐述了算法设计、模型构建、优化目标(如延迟、能耗、计算负载均衡)以及在Matlab平台上的代码实现过程,提供了完整的仿真验证与结果分析,展示了不同算法在卸载决策中的表现差异。; 适合人群:具备一定编程基础和优化算法知识,从事边缘计算、人工智能部署、智能优化等相关领域的科研人员及研究生;熟悉Matlab仿真工具的开发者。; 使用场景及目标:①研究边缘计算环境中深度学习模型的任务卸载机制;②对比分析多种改进粒子群算法在复杂优化问题中的性能优劣;③为实际系统中低延迟、高能效的AI推理部署提供算法选型与实现参考; 阅读建议:建议结合提供的Matlab代码进行实践操作,重点关注算法实现细节与参数设置,通过复现仿真结果深入理解不同启发式算法在卸载策略中的适用性与局限性,同时可拓展至其他智能优化算法的对比研究。
再來是 2) 基礎 VAP/VAPB 範本(與 Kyverno 規則等價) 說明: - labels-required:要求 Namespace 與核心工作負載具備指定 labels - immutable-namespace-meta:foundation 類命名空間 metadata 不可變更(名稱/關鍵標籤/註解) - require-signed-images:要求容器鏡像已簽章,使用 cosign 公鑰驗證(Admission 查驗 annotation/驗證報告) 2-1. labels-required.policy.yaml ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: labels-required labels: app.kubernetes.io/part-of: platform-governance app.kubernetes.io/component: policies spec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE","UPDATE"] resources: ["namespaces"] - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE","UPDATE"] resources: ["pods"] validations: - expression: "has(object.metadata.labels) && has(object.metadata.labels[\"namespace.io/team\"])" message: "Missing required label: namespace.io/team" - expression: "has(object.metadata.labels) && has(object.metadata.labels[\"namespace.io/environment\"])" message: "Missing required label: namespace.io/environment" - expression: "has(object.metadata.labels) && has(object.metadata.labels[\"namespace.io/lifecycle\"])" message: "Missing required label: namespace.io/lifecycle" auditAnnotations: - key: governance/labels-required value: "checked" ``` 2-2. labels-required.binding.yaml ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: name: labels-required-binding spec: policyName: labels-required validationActions: [Warn] # 將由 overlays 覆寫為 Warn/Audit/Deny matchResources: namespaceSelector: {} # 全域套用;可由 overlays 覆寫 ``` 2-3. immutable-namespace-meta.policy.yaml ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: immutable-namespace-meta labels: app.kubernetes.io/part-of: platform-governance app.kubernetes.io/component: policies spec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["UPDATE","DELETE"] resources: ["namespaces"] validations: - expression: "!(oldObject.metadata.name in [\"foundation\",\"platform\",\"infra\"]) || (object.metadata.name == oldObject.metadata.name)" message: "Core namespace name must not change" - expression: "!(oldObject.metadata.name in [\"foundation\",\"platform\",\"infra\"]) || (object.metadata.labels == oldObject.metadata.labels)" message: "Core namespace labels are immutable" - expression: "!(oldObject.metadata.name in [\"foundation\",\"platform\",\"infra\"]) || (object.metadata.annotations == oldObject.metadata.annotations)" message: "Core namespace annotations are immutable" auditAnnotations: - key: governance/immutable-namespace-meta value: "checked" ``` 2-4. immutable-namespace-meta.binding.yaml ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: name: immutable-namespace-meta-binding spec: policyName: immutable-namespace-meta validationActions: [Deny] # overlays 可覆寫 matchResources: namespaceSelector: {} ``` 2-5. require-signed-images.policy.yaml 說明: - 這裡示範以 image annotation 或 OCI subject annotation 作為簡化檢查條件。若您要真實串接 cosign 驗證,建議接 Admission Webhook 或使用 ImagePolicy(KEP-3299)/Kyverno verifyImages 的旁路結果。此處為與「Kyverno require-signed-images」等價邏輯的近似版:要求工作負載標註 signed=true 或帶有特定 attestation 註記。稍後可接實際驗證器。 ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: require-signed-images labels: app.kubernetes.io/part-of: platform-governance app.kubernetes.io/component: policies spec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: ["apps"] apiVersions: ["v1"] operations: ["CREATE","UPDATE"] resources: ["deployments","statefulsets","daemonsets"] - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE","UPDATE"] resources: ["pods"] paramKind: apiVersion: v1 kind: ConfigMap # 以 ConfigMap 提供 cosign 公鑰/策略參數 validations: - expression: | has(object.spec) && ( has(object.spec.template) ? has(object.spec.template.metadata.annotations["supplychain.signed"]) && object.spec.template.metadata.annotations["supplychain.signed"] == "true" : has(object.metadata.annotations["supplychain.signed"]) && object.metadata.annotations["supplychain.signed"] == "true" ) message: "Image must be signed: add annotation supplychain.signed=true after cosign verification" # 如需更嚴格:校驗指定 registry 或 digest 格式 - expression: | has(object.spec) && ( has(object.spec.template) ? size(object.spec.template.spec.containers) > 0 : has(object.spec.containers) && size(object.spec.containers) > 0 ) message: "Workload must define at least one container" auditAnnotations: - key: governance/require-signed-images value: "checked" ``` 2-6. require-signed-images.binding.yaml ```yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: name: require-signed-images-binding spec: policyName: require-signed-images validationActions: [Warn] # overlays 調整:dev=Warn, staging=Audit, prod=Deny matchResources: namespaceSelector: {} # 參數化:綁定 ConfigMap 作為參數(例如提供 cosign 公鑰/策略) params: name: cosign-root-keys namespace: governance-system ``` 3) overlays:dev/staging/prod 差異化 validationActions 每個 overlay 僅對 Binding 做 patches(保持 policy 穩定不動),並可選擇性限制套用範圍(namespaceSelector)或豁免特定 namespaces。 3-1. overlays/dev/kustomization.yaml ```yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../base/labels-required.policy.yaml - ../../base/labels-required.binding.yaml - ../../base/immutable-namespace-meta.policy.yaml - ../../base/immutable-namespace-meta.binding.yaml - ../../base/require-signed-images.policy.yaml - ../../base/require-signed-images.binding.yaml patches: - target: kind: ValidatingAdmissionPolicyBinding name: labels-required-binding patch: | - op: replace path: /spec/validationActions value: ["Warn"] - target: kind: ValidatingAdmissionPolicyBinding name: require-signed-images-binding patch: | - op: replace path: /spec/validationActions value: ["Warn"] - target: kind: ValidatingAdmissionPolicyBinding name: immutable-namespace-meta-binding patch: | - op: replace path: /spec/validationActions value: ["Audit"] # 觀察期,避免阻斷 ``` 3-2. overlays/staging/kustomization.yaml ```yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../base/labels-required.policy.yaml - ../../base/labels-required.binding.yaml - ../../base/immutable-namespace-meta.policy.yaml - ../../base/immutable-namespace-meta.binding.yaml - ../../base/require-signed-images.policy.yaml - ../../base/require-signed-images.binding.yaml patches: - target: kind: ValidatingAdmissionPolicyBinding name: labels-required-binding patch: | - op: replace path: /spec/validationActions value: ["Audit"] - target: kind: ValidatingAdmissionPolicyBinding name: require-signed-images-binding patch: | - op: replace path: /spec/validationActions value: ["Audit"] - target: kind: ValidatingAdmissionPolicyBinding name: immutable-namespace-meta-binding patch: | - op: replace path: /spec/validationActions value: ["Deny"] ``` 3-3. overlays/prod/kustomization.yaml ```yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../base/labels-required.policy.yaml - ../../base/labels-required.binding.yaml - ../../base/immutable-namespace-meta.policy.yaml - ../../base/immutable-namespace-meta.binding.yaml - ../../base/require-signed-images.policy.yaml - ../../base/require-signed-images.binding.yaml patches: - target: kind: ValidatingAdmissionPolicyBinding name: labels-required-binding patch: | - op: replace path: /spec/validationActions value: ["Deny"] - target: kind: ValidatingAdmissionPolicyBinding name: require-signed-images-binding patch: | - op: replace path: /spec/validationActions value: ["Deny"] - target: kind: ValidatingAdmissionPolicyBinding name: immutable-namespace-meta-binding patch: | - op: replace path: /spec/validationActions value: ["Deny"]
10-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值