문제
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 * 104
- 109 <= nums[i] <= 109
Follow-up:
Could you solve the problem in linear time and in
O(1)
space?
풀이
나의 풀이법
풀이 접근 과정
nums를 오름차순 정렬한 후 각 숫자의 cnt를 갱신했다.
최종 소스코드
class Solution {
fun majorityElement(nums: IntArray): Int {
nums.sort()
var maxCount = 0
var cnt = 0
var before = nums[0]
var answer = nums[0]
nums.forEach {
if (before != it) {
if (maxCount < cnt) {
maxCount = cnt
answer = before
}
cnt = 1
before = it
} else cnt++
}
if (maxCount < cnt) return before
else return answer
}
}
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 219. Contains Duplicate II (0) | 2023.06.30 |
---|---|
[LeetCode/Kotlin]Easy - 136. Single Number (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 217. Contains Duplicate (0) | 2023.06.10 |
[LeetCode/Kotlin]Easy - 66. Plus One (0) | 2023.06.10 |
[LeetCode/Kotlin]Easy - 9. Palindrome Number (0) | 2023.06.10 |