Skip to content

Commit 60ef2e2

Browse files
authored
Merge pull request #14 from argondev22/20251030/13-169-majority-element
Create 20251030.ts
2 parents 3de91ea + 4c20968 commit 60ef2e2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function majorityElement(nums: number[]): number {
2+
if (nums.length <= 2) {
3+
return nums[0]
4+
}
5+
6+
const arr1 = [nums[0]]
7+
const arr2 = []
8+
for (let i = 0; i < nums.length; i++) {
9+
if (nums[i] !== arr1[0]) {
10+
arr2.push(nums[i])
11+
} else {
12+
arr1.push(nums[i])
13+
}
14+
}
15+
16+
if (arr1.length > nums.length / 2) {
17+
return arr1[0]
18+
} else {
19+
return arr2[0]
20+
}
21+
};

0 commit comments

Comments
 (0)