Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/leetcode/169_Majority-Element/20251030.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function majorityElement(nums: number[]): number {
if (nums.length <= 2) {
return nums[0]
}
Comment on lines +2 to +4
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

長さが2の配列で[1, 2]のような異なる要素の場合、nums[0]が過半数要素ではない可能性があります。このロジックは不正確です。ただし、問題の制約上、過半数要素は必ず存在するため、長さ2の場合は両要素が同じであることが保証されていますが、長さ1の場合のみをチェックする方が明確です。

Copilot generated this review using guidance from repository custom instructions.

const arr1 = [nums[0]]
const arr2 = []
Comment on lines +6 to +7
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

変数名arr1arr2は意味が不明確です。majorityGroupminorityGroup、またはcandidateGroupotherGroupのように、何を格納しているかが分かる名前に変更することを推奨します。

Copilot generated this review using guidance from repository custom instructions.
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== arr1[0]) {
arr2.push(nums[i])
} else {
arr1.push(nums[i])
}
}
Comment on lines +8 to +14
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このアルゴリズムは3つ以上の異なる要素がある場合に正しく動作しません。例えば[1, 2, 3, 3, 3]の場合、arr1=[1,1]arr2=[2,3,3,3]となり、arr2[0]=2を返しますが、正解は3です。Boyer-Moore投票アルゴリズム、またはハッシュマップを使った頻度カウントの実装を推奨します。

Copilot generated this review using guidance from repository custom instructions.

if (arr1.length > nums.length / 2) {
return arr1[0]
} else {
return arr2[0]
}
Comment on lines +16 to +20
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

現在の実装は空間計算量O(n)を使用していますが、Boyer-Moore投票アルゴリズムを使用すれば空間計算量O(1)で解決できます。競技プログラミングでは効率的なアルゴリズムの選択が重要です。\n\n改善例:\ntypescript\nfunction majorityElement(nums: number[]): number {\n let candidate = nums[0];\n let count = 1;\n \n for (let i = 1; i < nums.length; i++) {\n if (count === 0) {\n candidate = nums[i];\n count = 1;\n } else if (nums[i] === candidate) {\n count++;\n } else {\n count--;\n }\n }\n \n return candidate;\n}\n

Copilot generated this review using guidance from repository custom instructions.
};