Last active
October 7, 2023 23:16
-
-
Save drawers/3cb8cc4cbb47a63d06b88acd3c3a7678 to your computer and use it in GitHub Desktop.
Clean Code-style refactor of Majority Element solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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