Files
illustrated-algorithm/two-sum/index.html
T
2026-08-24 04:35:13 +00:00

177 lines
6.9 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>001. 两数之和 – 图解</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>🟢 001. 两数之和 <span class="badge easy">简单</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: [2,7,11,15], target: 9, label: '示例1: nums=[2,7,11,15], target=9'},
{input: [3,2,4], target: 6, label: '示例2: nums=[3,2,4], target=6'},
{input: [3,3], target: 6, label: '示例3: nums=[3,3], target=6'},
];
let nums, target, steps, stepCtrl;
function buildSteps(arr, tgt) {
nums = arr; target = tgt;
steps = [];
const map = {};
steps.push({stage:'start', msg:'开始遍历数组,用哈希表记录已访问的元素', highlights:{}, mapKeys:[], idx:-1});
for (let i = 0; i < arr.length; i++) {
const complement = tgt - arr[i];
steps.push({stage:'check', msg:`检查 nums[${i}]=${arr[i]},需要的补数 complement = ${tgt} - ${arr[i]} = ${complement}`, highlights:{[i]:'orange'}, mapKeys:Object.entries(map), idx:i, complement});
if (complement in map) {
steps.push({stage:'found', msg:`找到!补数 ${complement} 在哈希表中,对应索引 ${map[complement]}`, highlights:{[i]:'green', [map[complement]]:'green'}, mapKeys:Object.entries(map), idx:i, result:[map[complement], i]});
return;
}
map[arr[i]] = i;
steps.push({stage:'store', msg:`补数 ${complement} 不在哈希表中,将 nums[${i}]=${arr[i]} → 索引 ${i} 存入哈希表`, highlights:{[i]:'blue'}, mapKeys:Object.entries(map), idx:i});
}
steps.push({stage:'done', msg:'遍历完毕,未找到满足条件的两个数', highlights:{}, mapKeys:Object.entries(map), idx:-1});
}
function render(step) {
if (!step) return;
const s = steps[step];
let viz = renderArray(nums, {highlights: s.highlights});
if (s.complement !== undefined) {
viz += '<div style="margin-top:8px;color:#64748b;">complement = ' + s.complement + '</div>';
}
$('vizArea').innerHTML = viz;
let detail = '<div class="calc-block">' + s.msg + '</div>';
if (s.mapKeys && s.mapKeys.length > 0) {
detail += '<div style="margin-top:8px;"><b>哈希表:</b>';
s.mapKeys.forEach(([k,v]) => { detail += `<code>${k}→${v}</code> `; });
detail += '</div>';
}
$('detailContent').innerHTML = detail;
if (s.stage === 'found') {
$('resultContent').innerHTML = `<div class="final-answer">返回 <b>[${s.result}]</b><br>nums[${s.result[0]}] + nums[${s.result[1]}] = ${nums[s.result[0]]} + ${nums[s.result[1]]} = ${target}</div>`;
} else if (s.stage === 'done') {
$('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">未找到答案</div>';
}
$('hintText').textContent = s.msg;
const stages = ['start→开始','check→检查','store→存入','found→找到'];
$('pipeline').innerHTML = stages.map(st => {
const [key, label] = st.split('→');
return `<span class="pipe-step ${s.stage===key?'active':''}">${label}</span>`;
}).join('<i>→</i>');
}
function init() {
const sel = $('exampleSelect');
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
$('inputArea').value = 'nums=[2,7,11,15], target=9';
buildSteps(examples[0].input, examples[0].target);
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=\[([^\]]+)\].*target=(\d+)/);
if (!m) { alert('格式: nums=[2,7,11,15], target=9'); return; }
const arr = m[1].split(',').map(Number);
const tgt = parseInt(m[2]);
buildSteps(arr, tgt);
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}], target=${e.target}`;
buildSteps(e.input, e.target);
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 twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []`, {lang:'Python'});
})();
</script>
</body>
</html>