Time Complexity:
Spcae Complexity:
# dict 사용
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = dict()
half = len(nums) // 2
for num in nums:
if num not in count:
count[num] = 0
count[num] += 1
if count[num] > half:
return num
# dict의 sub class인 Counter 사용
import collections
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counter = collections.Counter(nums)
return max(counter.keys(), key=counter.get)
Time Complexity:
Spcae Complexity: or <- if In-Place not allowed
class Solution:
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
Time Complexity:
Spcae Complexity:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate