[Leetcode] 169. Majority Element
[Leetcode] 169. Majority Element

[Leetcode] 169. Majority Element

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 09์›” 12์ผ

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

Given an arrayย numsย of sizeย n, returnย the majority element.
๋ฐฐ์—ด์—์„œ ๊ณผ๋ฐ˜์ˆ˜ ์š”์†Œ๋ฅผ ์ฐพ์œผ๋ฉด ๋œ๋‹ค. ๊ณผ๋ฐ˜์ˆ˜ ์š”์†Œ๊ฐ€ ํ•ญ์ƒ ์กด์žฌํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฏ€๋กœ ๋ฌธ์ œ์˜ ๋‚œ์ด๋„๊ฐ€ ์‰ฌ์›Œ์ง„๋‹ค.
ย 

โš™๏ธย Python

from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: return max(nums, key=nums.count)
ย 
ํŒŒ์ด์ฌ์˜ ๊ฒฝ์šฐ๋Š” ๋งค์šฐ ์‰ฝ๋‹ค. ๋ฌผ๋ก  ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(nยฒ) ์ด์ง€๋งŒ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€๋ฆฐ๋‹ค. max ํ•จ์ˆ˜์˜ key๋กœ ํ•จ์ˆ˜๊ฐ€ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฑธ ์•„๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค.
ย 

๐Ÿ’กย ๋” ์ข‹์€ ์•„์ด๋””์–ด

class Solution: def majorityElement(self, nums: List[int]) -> int: count = 1 major = nums[0] length = len(nums) for i in range(1, length): if count == 0: count += 1 major = nums[i] elif nums[i] == major: count += 1 else: count -= 1 return major
์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(n) ์ธ ์ข‹์€ ์ฝ”๋“œ๋‹ค. ์ด ์ฝ”๋“œ๋Š” ๊ณผ๋ฐ˜์ˆ˜ ์›์†Œ๊ฐ€ ์ ˆ๋ฐ˜ ์ด์ƒ ๋“ฑ์žฅํ•œ๋‹ค๋Š” ํŠน์„ฑ์„ ์ด์šฉํ•˜์—ฌ, ๋งˆ์ง€๋ง‰๊นŒ์ง€ ๋‚จ๋Š” ์›์†Œ๊ฐ€ ์‹ค์ œ๋กœ ๊ณผ๋ฐ˜์ˆ˜ ์›์†Œ์ž„์„ ๋ณด์žฅํ•œ๋‹ค.
ย 

๐Ÿ“Œย ์†Œ๊ฐ

ํŒŒ์ด์ฌ์€ ๋ฉ”์†Œ๋“œ๋ฅผ ๋งŽ์ด ์•„๋Š” ๊ฒŒ ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™๋‹ค.
ย 

๋Œ“๊ธ€

guest