Skip to content

Instantly share code, notes, and snippets.

@drawers
Last active October 7, 2023 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drawers/3cb8cc4cbb47a63d06b88acd3c3a7678 to your computer and use it in GitHub Desktop.
Save drawers/3cb8cc4cbb47a63d06b88acd3c3a7678 to your computer and use it in GitHub Desktop.
Clean Code-style refactor of Majority Element solution
class Solution {
private var count = 0
private var candidate: Int? = null
fun majorityElement(nums: IntArray): Int {
for (num in nums) {
candidate = updateCandidateForZeroCount(num)
count = updateCountForCandidate(num)
}
return candidate!!
}
private fun updateCandidateForZeroCount(num: Int): Int? {
if (count == 0) {
return num
}
return candidate
}
private fun updateCountForCandidate(num: Int): Int {
return if (num == candidate) {
count + 1
} else {
count - 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment