[Leetcode] 169. Majority Element
問題のショートカット
Time Complexity: O(n)O(n)O(n)
Spcae Complexity: O(n)O(n)O(n)
Time Complexity: O(nlogn)O(n\log n)O(nlogn)
Spcae Complexity: O(1)O(1)O(1) or O(n)O(n)O(n) <- if In-Place not allowed
Time Complexity: O(n)O(n)O(n)
Spcae Complexity: O(1)O(1)O(1)
一般入力の場合:
hash map
Time Complexity: O(n)O(n)O(n)
Spcae Complexity: O(n)O(n)O(n)
# 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)
2つの数値のみを入力します。
sort
Time Complexity: O(nlogn)O(n\log n)O(nlogn)
Spcae Complexity: O(1)O(1)O(1) or O(n)O(n)O(n) <- if In-Place not allowed
class Solution:
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
Boyer-Moore Voting Algorithm
Time Complexity: O(n)O(n)O(n)
Spcae Complexity: O(1)O(1)O(1)
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
Reference
この問題について([Leetcode] 169. Majority Element), 我々は、より多くの情報をここで見つけました https://velog.io/@haebin/Leetcode-169.-Majority-Elementテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol