Skip to content
Merged
Show file tree
Hide file tree
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
37 changes: 37 additions & 0 deletions src/main/kotlin/exercise100/easy/id169/Description169.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
[//]: # (Copyright [2023] [Anton Kotler kotler.developer@gmail.com] License MIT)

# Majority Element

![Difficulty](https://img.shields.io/badge/Difficulty-Easy-61904f)

Given an array `nums` of size `n`, return the majority element.
The majority element is the element that appears more than `|n / 2|` times.
You may assume that the majority element always exists in the array.

Example 1:

```
Input: nums = [3,2,3]
Output: 3
```

Example 2:

```
Input: nums = [2,2,1,1,1,2,2]
Output: 2
```

Constraints:

- `n == nums.length`
- `1 <= n <= 5 * 10^4`
- `-10^9 <= nums[i] <= 10^9`

Follow-up: Could you solve the problem in linear time and in `O(1)` space?

| ID | Description | Solution | Test | Difficulty |
|:---:|:-----------------|:----------------------------:|:-----------------------------------------------------------------------------------:|:----------:|
| 169 | Majority Element | [solution](./Solution169.kt) | [test](../../../../../../src/test/kotlin/exercise100/easy/id169/Solution169Test.kt) | Easy |

:top: [Back to all topics](https://github.com/kotler-dev/kotlin-leetcode)
19 changes: 19 additions & 0 deletions src/main/kotlin/exercise100/easy/id169/Solution169.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package exercise100.easy.id169

class Solution169 {
fun majorityElement(nums: IntArray): Int {
val hm = HashMap<Int, Int>()
nums.forEach {
val n = hm[it]
if (n == null) hm[it] = 0
if (n != null) hm[it] = n + 1
}
return hm.maxBy { n -> n.value }.key
}

/*



*/
}
26 changes: 26 additions & 0 deletions src/test/kotlin/exercise100/easy/id169/Solution169Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package exercise100.easy.id169

import io.kotest.assertions.print.print
import io.kotest.core.spec.style.FunSpec
import io.kotest.datatest.WithDataTestName
import io.kotest.datatest.withData
import io.kotest.matchers.shouldBe

data class TestCase(
val prices: IntArray,
val expected: Int,
) : WithDataTestName {
override fun dataTestName(): String = expected.print().value
}

class Solution169Test : FunSpec({
context("shouldBe") {
withData(
nameFn = { "Input: ${it.prices.print().value}, Expected: ${it.expected.print().value}" },
TestCase(prices = intArrayOf(3, 2, 3), expected = 3),
TestCase(prices = intArrayOf(2, 2, 1, 1, 1, 2, 2), expected = 2),
) { (prices, expected) ->
Solution169().majorityElement(prices) shouldBe expected
}
}
})