Files
2026-08-24 04:35:13 +00:00

127 lines
6.7 KiB
HTML
Raw Permalink 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>097. 多数元素 – 图解</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>🟢 097. 多数元素 <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:[3,2,3], label:'示例1: [3,2,3]'},
{input:[2,2,1,1,1,2,2], label:'示例2: [2,2,1,1,1,2,2]'},
{input:[1], label:'示例3: [1]'},
];
let nums, steps, stepCtrl;
function buildSteps(arr) {
nums=[...arr];steps=[];let c=null,cnt=0;const hist=[];
steps.push({stage:'init',msg:'Boyer-Moore投票:同+1异-1,为0换人',idx:-1,candidate:null,count:0,history:[]});
for(let i=0;i<arr.length;i++){
if(cnt===0){c=arr[i];cnt=1;hist.push({i,v:arr[i],c:cnt,a:'换'});steps.push({stage:'change',msg:`计数器0→换候选者为${arr[i]}`,idx:i,candidate:c,count:cnt,history:[...hist]});}
else if(arr[i]===c){cnt++;hist.push({i,v:arr[i],c:cnt,a:'同'});steps.push({stage:'same',msg:`${arr[i]}==${c}→+1 count=${cnt}`,idx:i,candidate:c,count:cnt,history:[...hist]});}
else{cnt--;hist.push({i,v:arr[i],c:cnt,a:'异'});steps.push({stage:'diff',msg:`${arr[i]}≠${c}→-1 count=${cnt}`,idx:i,candidate:c,count:cnt,history:[...hist]});}
}
steps.push({stage:'done',msg:`多数元素=${c}`,idx:-1,candidate:c,count:cnt,history:[...hist]});
}
function render(step) {
const s=steps[step];const hl={};if(s.idx>=0)hl[s.idx]='orange';for(let i=0;i<=Math.min(s.idx,nums.length-1);i++){if(nums[i]===s.candidate&&!hl[i])hl[i]='green';}
let viz=renderArray(nums,{highlights:hl});
viz+=`<div style="margin-top:12px;padding:12px;background:#f8fafc;border-radius:8px;display:flex;gap:16px;align-items:center;"><div><b>候选者:</b><span style="font-size:24px;font-weight:700;color:var(--blue);">${s.candidate!==null?s.candidate:'—'}</span></div><div><b>计数:</b><div style="display:flex;align-items:center;gap:4px;"><div style="width:${Math.max(0,s.count*28)}px;height:20px;background:var(--blue);border-radius:4px;"></div><span style="font-weight:700;">${s.count}</span></div></div></div>`;
if(s.history&&s.history.length>0){viz+='<div style="margin-top:12px;"><b>投票历史:</b></div><div style="display:flex;align-items:flex-end;gap:4px;height:60px;margin-top:4px;">';const mx=Math.max(...s.history.map(h=>Math.abs(h.c)),1);s.history.forEach(h=>{const pct=Math.max(4,(Math.abs(h.c)/mx)*50);const bg=h.a==='换'?'var(--orange)':h.a==='同'?'var(--green)':'var(--red)';viz+=`<div style="width:28px;height:${pct}px;background:${bg};border-radius:3px 3px 0 0;"></div>`;});viz+='</div><div style="display:flex;gap:4px;">';s.history.forEach(h=>{viz+=`<div style="width:28px;text-align:center;font-size:9px;">${h.v}</div>`;});viz+='</div>';}
$('vizArea').innerHTML=viz;
$('detailContent').innerHTML='<div class="calc-block">'+s.msg+'</div>'+`<div class="current-answer">候选:<b>${s.candidate}</b> 计数:<b>${s.count}</b></div>`;
if(s.stage==='done') $('resultContent').innerHTML=`<div class="final-answer">多数元素=<b>${s.candidate}</b></div>`;
$('hintText').textContent=s.msg;
const stages=['init→初始化','change→更换','same→相同','diff→不同','done→完成'];
$('pipeline').innerHTML=stages.map(x=>{const[k,l]=x.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='[3,2,3]';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 a=JSON.parse($('inputArea').value);buildSteps(a);stepCtrl.setSteps(steps.map((_,i)=>i));render(0);}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 majorityElement(nums):
candidate = None
count = 0
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate`, {lang:'Python'});
})();
</script>
</body>
</html>