[Q] [Easy]
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.
- 일단 in-place 문제가 아니면 좀 더 편하게 풀 수 있는 것 같다.
- 라고 생각했는데 제출하니까 틀렸다고 한다.
- 아무리봐도 틀린 부분이 없는 것 같아 colab 에서 돌려봤더니 맞게 답이 나오는데 어디서 연산이 잘못 되었을까..
- n 이 $len(nums)$ 라고 했는데 내가 다른 변수로 써서 그런가 해서 m 으로 바꿔보기도 하고, float 연산을 지정해줘야 하나 해서 $n = float(len(nums)/2)$ 로 변경도 했지만 실패
- 일단 틀린 문제는 nums = [3, 3, 4] 일 때이다.
- float이 들어가서 문제였나 싶어서 m[$= len(nums)/2$] 을 // 연산으로 바꿔주고 아래 비교하는 부분을 "이상 [>=]" 이 아닌 "초과 [>]" 로 변경해주었더니 됐다.
# Wrong Answer
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) / 2
ele = list(set(nums))
for i in ele:
if nums.count(i) >= n :
ans = i
return ans
# Answer
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m = len(nums) // 2
ele = list(set(nums))
for i in ele:
if nums.count(i) > m :
ans = i
return ans