Files
illustrated-algorithm/subarray-sum-equals-k/index.html
T

197 lines
7.7 KiB
HTML
Raw Normal View History

<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>010. 和为 K 的子数组 – 图解</title>
<link rel="stylesheet" href="../shared/style.css">
<style>
/* page-specific overrides */
.vis-area { min-height: 120px; padding: 16px 0; }
.code-section { margin-top: 16px; }
</style>
</head>
<body>
<div class="container">
<h1>🟡 010. 和为 K 的子数组 <span class="badge medium">中等</span></h1>
<p class="subtitle">分类:子串 | LeetCode Hot 100</p>
<!-- 控制面板 -->
<div class="controls" id="controls">
<label for="inputArea">输入:</label>
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
<button id="applyBtn" class="primary">生成图解</button>
<select id="exampleSelect"></select>
<span style="flex:1"></span>
<button id="prevBtn">◀ 上一步</button>
<button id="nextBtn">下一步 ▶</button>
<button id="jumpBtn">⏭ 跳到结果</button>
<button id="autoBtn">自动播放</button>
<button id="resetBtn">重置</button>
</div>
<!-- 步骤流水线 -->
<div class="pipeline" id="pipeline"></div>
<!-- 提示条 -->
<div class="hint info" id="hintBox">
<span id="stepInfo"></span><br>
<span id="hintText"></span>
</div>
<!-- 可视化面板 -->
<div class="panels">
<div class="panel" id="mainPanel">
<h3>📊 可视化</h3>
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
</div>
<div class="panel-grid">
<div class="panel" id="detailPanel">
<h3>📝 当前步骤详情</h3>
<div id="detailContent">等待开始...</div>
</div>
<div class="panel" id="resultPanel">
<h3>✅ 结果</h3>
<div id="resultContent">等待完成...</div>
</div>
</div>
</div>
<!-- 代码 -->
<div class="panel code-section">
<h3>💻 参考代码(Python)</h3>
<div id="codeArea"></div>
</div>
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
</div>
<script src="../shared/algo-viz.js"></script>
<script>
"use strict";
(function() {
// ========== Algorithm Logic ==========
const examples = [
{input: [1,1,1], k: 2, label: '示例1: nums=[1,1,1], k=2'},
{input: [1,2,3], k: 3, label: '示例2: nums=[1,2,3], k=3'},
{input: [1,-1,0], k: 0, label: '示例3: nums=[1,-1,0], k=0'},
];
let nums, k, steps, stepCtrl;
function buildSteps(arr, target) {
nums = arr; k = target; steps = [];
const prefixMap = {0: 1};
let prefixSum = 0, count = 0;
steps.push({stage:'init', msg:'初始化:前缀和=0,哈希表记录 {0:1}(前缀和0出现1次)', idx:-1, prefixSum:0, prefixMap:{0:1}, count:0, num:0});
for (let i = 0; i < arr.length; i++) {
prefixSum += arr[i];
const need = prefixSum - target;
steps.push({stage:'calc', msg:`i=${i},累加 nums[${i}]=${arr[i]},前缀和=${prefixSum},需要找 ${prefixSum}-${target}=${need}`, idx:i, prefixSum, prefixMap:{...prefixMap}, count, need, num:arr[i]});
if (need in prefixMap) {
const found = prefixMap[need];
count += found;
steps.push({stage:'found', msg:`前缀和 ${need} 在哈希表中出现 ${found} 次,即存在 ${found} 个子数组和为 ${target},累计count=${count}`, idx:i, prefixSum, prefixMap:{...prefixMap}, count, need, num:arr[i]});
}
prefixMap[prefixSum] = (prefixMap[prefixSum] || 0) + 1;
steps.push({stage:'store', msg:`将前缀和 ${prefixSum} 存入哈希表,出现次数 +1`, idx:i, prefixSum, prefixMap:{...prefixMap}, count, num:arr[i]});
}
steps.push({stage:'done', msg:`遍历完毕,和为 ${target} 的子数组个数为 ${count}`, idx:-1, prefixSum, prefixMap:{...prefixMap}, count, num:0});
}
function render(step) {
const s_ = steps[step];
const hl = {};
if (s_.idx >= 0) hl[s_.idx] = 'orange';
let viz = '<div style="margin-bottom:6px;"><b>数组:</b></div>';
viz += renderArray(nums, {highlights: hl});
if (s_.idx >= 0) {
viz += '<div style="margin-top:10px;"><b>前缀和序列:</b></div>';
const prefixArr = [];
let ps = 0;
for (let i = 0; i < nums.length; i++) { ps += nums[i]; prefixArr.push(ps); }
const phl = {};
if (s_.idx >= 0) phl[s_.idx] = 'purple';
viz += renderArray(prefixArr, {highlights: phl});
}
viz += '<div class="table-wrap" style="margin-top:12px;"><table><tr><th>前缀和</th><th>出现次数</th></tr>';
if (s_.stage === 'found' && s_.need in s_.prefixMap) {
viz += `<tr style="background:#dcfce7;"><td><code>${s_.need}</code></td><td style="color:var(--green);font-weight:700;">${s_.prefixMap[s_.need]}</td></tr>`;
}
Object.entries(s_.prefixMap).sort((a,b)=>Number(a[0])-Number(b[0])).forEach(([key, val]) => {
const isNeed = s_.stage === 'found' && String(key) === String(s_.need);
if (!isNeed) {
viz += `<tr><td><code>${key}</code></td><td>${val}</td></tr>`;
}
});
viz += '</table></div>';
$('vizArea').innerHTML = viz;
let detail = '<div class="calc-block">' + s_.msg + '</div>';
detail += `<div style="margin-top:8px;">当前 count = <b>${s_.count}</b></div>`;
$('detailContent').innerHTML = detail;
if (s_.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">和为 ${k} 的子数组个数 = <b>${s_.count}</b></div>`;
}
$('hintText').textContent = s_.msg;
const stages = ['init→开始','calc→计算','found→命中','store→存储','done→完成'];
$('pipeline').innerHTML = stages.map(st => {
const [k_,l] = st.split('→');
return `<span class="pipe-step ${s_.stage===k_?'active':''}">${l}</span>`;
}).join('<i>→</i>');
}
function init() {
const sel = $('exampleSelect');
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
$('inputArea').value = 'nums=[1,1,1], k=2';
buildSteps(examples[0].input, examples[0].k);
stepCtrl = new StepController({onStep: render});
stepCtrl.setSteps(steps.map((_,i)=>i));
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
$('applyBtn').onclick = () => {
const m = $('inputArea').value.match(/nums=\[([^\]]+)\].*k=(-?\d+)/);
if (!m) { alert('格式: nums=[1,1,1], k=2'); return; }
const arr = m[1].split(',').map(Number);
const k_ = parseInt(m[2]);
buildSteps(arr, k_); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = `nums=[${e.input}], k=${e.k}`;
buildSteps(e.input, e.k); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
};
$('prevBtn').onclick = () => stepCtrl.prev();
$('nextBtn').onclick = () => stepCtrl.next();
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
}
init();
$('codeArea').innerHTML = renderCode(`def subarraySum(nums, k):
from collections import defaultdict
prefix_count = defaultdict(int)
prefix_count[0] = 1
prefix_sum = 0
count = 0
for num in nums:
prefix_sum += num
if prefix_sum - k in prefix_count:
count += prefix_count[prefix_sum - k]
prefix_count[prefix_sum] += 1
return count`, {lang:'Python'});
})();
</script>
</body>
</html>