-
Notifications
You must be signed in to change notification settings - Fork 0
Create 20251030.ts #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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] | ||
| } | ||
|
|
||
| const arr1 = [nums[0]] | ||
| const arr2 = [] | ||
|
Comment on lines
+6
to
+7
|
||
| 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
|
||
|
|
||
| if (arr1.length > nums.length / 2) { | ||
| return arr1[0] | ||
| } else { | ||
| return arr2[0] | ||
| } | ||
|
Comment on lines
+16
to
+20
|
||
| }; | ||
There was a problem hiding this comment.
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の場合のみをチェックする方が明確です。