173 lines
7.4 KiB
HTML
173 lines
7.4 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-Hans">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>006. 三数之和 – 图解</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>🟡 006. 三数之和 <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,0,1,2,-1,-4], label: '示例1: [-1,0,1,2,-1,-4]'},
|
||
{input: [0,1,1], label: '示例2: [0,1,1]'},
|
||
{input: [0,0,0], label: '示例3: [0,0,0]'},
|
||
];
|
||
let nums, steps, stepCtrl;
|
||
|
||
function buildSteps(arr) {
|
||
nums = [...arr].sort((a,b) => a - b); steps = [];
|
||
const result = [];
|
||
steps.push({stage:'sort', msg:`排序: [${arr}] → [${nums}]`, arr:[...nums], i:-1, l:-1, r:-1, triplets:[], currentSum:null});
|
||
for (let i = 0; i < nums.length - 2; i++) {
|
||
if (i > 0 && nums[i] === nums[i-1]) continue;
|
||
let l = i + 1, r = nums.length - 1;
|
||
steps.push({stage:'fix', msg:`固定 nums[${i}]=${nums[i]},双指针 [${l}..${r}]`, arr:[...nums], i, l, r, triplets:JSON.parse(JSON.stringify(result)), currentSum:null});
|
||
while (l < r) {
|
||
const sum = nums[i] + nums[l] + nums[r];
|
||
steps.push({stage:'calc', msg:`${nums[i]}+${nums[l]}+${nums[r]}=${sum}` + (sum===0?' ✓':sum<0?' → L右移':' → R左移'), arr:[...nums], i, l, r, triplets:JSON.parse(JSON.stringify(result)), currentSum:sum});
|
||
if (sum === 0) {
|
||
result.push([nums[i], nums[l], nums[r]]);
|
||
steps.push({stage:'found', msg:`找到 [${nums[i]},${nums[l]},${nums[r]}]`, arr:[...nums], i, l, r, triplets:JSON.parse(JSON.stringify(result)), currentSum:0});
|
||
while (l < r && nums[l] === nums[l+1]) l++;
|
||
while (l < r && nums[r] === nums[r-1]) r--;
|
||
l++; r--;
|
||
} else if (sum < 0) { l++; } else { r--; }
|
||
}
|
||
}
|
||
steps.push({stage:'done', msg:`共找到 ${result.length} 个三元组`, arr:[...nums], i:-1, l:-1, r:-1, triplets:JSON.parse(JSON.stringify(result)), currentSum:null});
|
||
}
|
||
|
||
function render(step) {
|
||
const s = steps[step];
|
||
const hl = {};
|
||
if (s.i>=0) hl[s.i] = s.stage==='found'?'green':'purple';
|
||
if (s.l>=0) hl[s.l] = s.stage==='found'?'green':'orange';
|
||
if (s.r>=0) hl[s.r] = s.stage==='found'?'green':'blue';
|
||
const pointers = {};
|
||
if (s.i>=0) pointers['i']=s.i; if (s.l>=0) pointers['L']=s.l; if (s.r>=0) pointers['R']=s.r;
|
||
let viz = renderArray(s.arr, {highlights:hl, pointers});
|
||
if (s.currentSum !== null) viz += `<div style="margin-top:8px;">和 = <b style="color:${s.currentSum===0?'var(--green)':s.currentSum<0?'var(--blue)':'var(--red)'};">${s.currentSum}</b></div>`;
|
||
$('vizArea').innerHTML = viz;
|
||
let detail = '<div class="calc-block">' + s.msg + '</div>';
|
||
if (s.triplets.length > 0) { s.triplets.forEach((t,i)=>{ detail += `<div><code>${i+1}. [${t.join(', ')}]</code></div>`; }); }
|
||
$('detailContent').innerHTML = detail;
|
||
if (s.stage === 'done') {
|
||
if (s.triplets.length > 0) $('resultContent').innerHTML = `<div class="final-answer">返回 <b>${JSON.stringify(s.triplets)}</b></div>`;
|
||
else $('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">未找到</div>';
|
||
}
|
||
$('hintText').textContent = s.msg;
|
||
const stages = ['sort→排序','fix→固定','calc→计算','found→找到','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 = '[-1,0,1,2,-1,-4]';
|
||
buildSteps(examples[0].input);
|
||
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 = () => {
|
||
try { const arr = JSON.parse($('inputArea').value); buildSteps(arr); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length; }
|
||
catch(e) { alert('请输入合法 JSON 数组'); }
|
||
};
|
||
$('exampleSelect').onchange = () => {
|
||
const e = examples[parseInt($('exampleSelect').value)];
|
||
$('inputArea').value = JSON.stringify(e.input); buildSteps(e.input); 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 threeSum(nums):
|
||
nums.sort()
|
||
res = []
|
||
for i in range(len(nums) - 2):
|
||
if i > 0 and nums[i] == nums[i-1]:
|
||
continue
|
||
l, r = i + 1, len(nums) - 1
|
||
while l < r:
|
||
s = nums[i] + nums[l] + nums[r]
|
||
if s == 0:
|
||
res.append([nums[i], nums[l], nums[r]])
|
||
while l < r and nums[l] == nums[l+1]: l += 1
|
||
while l < r and nums[r] == nums[r-1]: r -= 1
|
||
l += 1; r -= 1
|
||
elif s < 0: l += 1
|
||
else: r -= 1
|
||
return res`, {lang:'Python'});
|
||
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html> |