Files
illustrated-algorithm/search-insert-position/index.html
T

191 lines
7.6 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>063. 搜索插入位置 – 图解</title>
<link rel="stylesheet" href="../shared/style.css">
<style>
.vis-area { min-height: 120px; padding: 16px 0; }
.code-section { margin-top: 16px; }
.range-label { margin-top: 6px; font-size: 13px; color: var(--text-secondary); }
</style>
</head>
<body>
<div class="container">
<h1>🟢 063. 搜索插入位置 <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="nums=[1,3,5,6], target=5">
<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() {
const examples = [
{nums:[1,3,5,6], target:5, label:'示例1: target=5'},
{nums:[1,3,5,6], target:2, label:'示例2: target=2'},
{nums:[1,3,5,6], target:7, label:'示例3: target=7'},
{nums:[1,3,5,6], target:0, label:'示例4: target=0'},
];
let steps, stepCtrl;
function buildSteps(nums, target) {
steps = [];
let left = 0, right = nums.length - 1;
steps.push({stage:'init', msg:`初始化:left=${left}, right=${right}`, left, right, mid:-1, found:false, ans:-1});
while (left <= right) {
const mid = Math.floor((left + right) / 2);
steps.push({stage:'calc', msg:`计算 mid = ⌊(${left}+${right})/2⌋ = ${mid},nums[${mid}] = ${nums[mid]}`, left, right, mid, found:false, ans:-1});
if (nums[mid] === target) {
steps.push({stage:'found', msg:`nums[${mid}] = ${nums[mid]} == ${target},找到目标!返回 ${mid}`, left, right, mid, found:true, ans:mid});
return;
} else if (nums[mid] < target) {
steps.push({stage:'goRight', msg:`nums[${mid}] = ${nums[mid]} < ${target},目标在右半区,left = ${mid} + 1 = ${mid+1}`, left:mid+1, right, mid, found:false, ans:-1});
left = mid + 1;
} else {
steps.push({stage:'goLeft', msg:`nums[${mid}] = ${nums[mid]} > ${target},目标在左半区,right = ${mid} - 1 = ${mid-1}`, left, right:mid-1, mid, found:false, ans:-1});
right = mid - 1;
}
}
steps.push({stage:'done', msg:`循环结束,left=${left} > right=${right},插入位置为 ${left}`, left, right, mid:-1, found:false, ans:left});
}
function render(step) {
const s = steps[step];
const arr = JSON.parse($('inputArea').value.match(/nums=\[([^\]]+)\]/)?.[1] || '[]') || [1,3,5,6];
const hl = highlightRange(arr, s.left, s.right, 'cyan');
if (s.mid >= 0 && s.mid < arr.length) hl[s.mid] = s.found ? 'green' : 'orange';
const pointers = {};
if (s.left >= 0 && s.left < arr.length) pointers['L'] = s.left;
if (s.right >= 0 && s.right < arr.length) pointers['R'] = s.right;
if (s.mid >= 0 && s.mid < arr.length) pointers['mid'] = s.mid;
let viz = renderArray(arr, {highlights: hl, pointers});
viz += `<div class="range-label">搜索范围: [${s.left}..${s.right}] | `;
if (s.mid >= 0) viz += `nums[${s.mid}] = ${arr[s.mid]} | `;
viz += `target = ${JSON.parse($('inputArea').value.match(/target=(\d+)/)?.[0]?.split('=')[1] || '5')}</div>`;
if (s.found) {
viz += `<div class="current-answer">✅ 找到!目标 ${arr[s.mid]} 在索引 <b>${s.mid}</b></div>`;
}
$('vizArea').innerHTML = viz;
let detail = `<div class="calc-block">${s.msg}</div>`;
detail += `<div style="margin-top:6px;font-size:13px;color:var(--text-secondary);">left = ${s.left} right = ${s.right}`;
if (s.mid >= 0) detail += ` mid = ${s.mid}`;
detail += '</div>';
$('detailContent').innerHTML = detail;
if (s.stage === 'done' || s.found) {
const ans = s.found ? s.ans : s.ans;
$('resultContent').innerHTML = `<div class="final-answer">${s.found ? '找到目标' : '未找到目标,插入位置'}:<b>${ans}</b><br>时间复杂度 O(log n)</div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','calc→计算mid','goRight→右移','goLeft→左移','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 = 'nums=[1,3,5,6], target=5';
buildSteps(examples[0].nums, 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 = () => {
try {
const m = $('inputArea').value.match(/nums=\[([^\]]+)\].*target=(-?\d+)/);
if (!m) { alert('格式: nums=[1,3,5,6], target=5'); 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}`;
} catch(e) { alert('输入格式错误'); }
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = `nums=[${e.nums}], target=${e.target}`;
buildSteps(e.nums, 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 searchInsert(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left # left 就是插入位置`, {lang:'Python'});
})();
</script>
</body>
</html>