Leetcode - Majority Element

Leetcode - Majority Element

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

Daily Leetcode

Hits

๋ฌธ์ œ ๋งํฌ

๋ฌธ์ œ๋Š” ํ•ด์„ํ•˜๋ฉด ๊ณผ๋ฐ˜์ˆ˜ ์ด์ƒ ๋“ฑ์žฅํ•œ ์›์†Œ๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด ๋œ๋‹ค. ์ด๋ฒˆ ๋ฌธ์ œ๋Š” ์ด 3๊ฐœ์˜ ์†”๋ฃจ์…˜์ด ์ œ๊ณต๋œ๋‹ค.

๐Ÿ”‘ Naive Solution

์—ญ์‹œ ์ฒ˜์Œ์—๋Š” ๊ฐ€์žฅ ์›์ดˆ์ ์ธ ๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค. ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค์–ด์„œ ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ๋ชจ๋‘ ์ €์žฅํ•ด๋‘๊ณ  ๊ทธ ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์ •๋ ฌํ•˜๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™๋‹ค. (์‚ฌ์‹ค ๋ณ„๋กœ์ž„)

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        # Naive Solutions

        num_cnt = dict()

        for num in nums:
            num_cnt[num] = num_cnt.get(num, 0)+1

        num_cnt = sorted(num_cnt.items(), key=lambda x:-x[1])
        ret = num_cnt[0][0]

        return ret

์ฝ”๋“œ๋Š” ๋ง ๊ทธ๋Œ€๋กœ ๊ตฌํ˜„ํ•ด๋‘” ๊ฒƒ์ด๊ณ  ๋ถ„์„์„ ํ•ด๋ณด์ž

  • Time Complexity : O(nlogn)
  • Space Complexity : O(n)

์—ฌ๊ธฐ์„œ ๋ฉด์ ‘๊ด€์ด Time / Space ์ค‘ ํ•˜๋‚˜๋ฅผ ์ค„์—ฌ๋ณด๋ผ๊ณ  ํ•œ๋‹ค.

๐Ÿงฑ Better Solution

๊ณผ๋ฐ˜์ˆ˜์— ์ง‘์ค‘ํ•ด๋ณด์ž. ๊ตณ์ด ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์„ธ์„œ ์ •๋ ฌํ•  ํ•„์š”์—†์ด ๋ฐ์ดํ„ฐ๋ฅผ ์ •๋ ฌํ•˜๊ณ  ๊ณผ๋ฐ˜์ˆ˜๋Š” ์–ด์ฐŒ๋๋˜ len(nums)//2 ์ธ๋ฑ์Šค์— ์žˆ์ง€ ์•Š์„๊นŒ? ์ด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ฝ”๋“œ๋ฅผ ์งœ๋ณด์ž

class Solution:
    def majorityElement(self, nums: List[int]) -> int:

        # Better Solution
        nums.sort()
        return nums[len(nums)//2]
  • Time Complexity : O(nlogn)
  • Space Complexity : O(1)

๋ฉด์ ‘๊ด€์ด ์‹œ๊ฐ„๋ณต์žก๋„๋„ ์„ ํ˜•์œผ๋กœ ๋ถ€ํƒํ•œ๋‹ค.

๐Ÿ’‰ Best Solution (Boyer Moore Voting)

์‚ฌ์‹ค ์ด๊ฑด ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์•Œ์•„์•ผ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ํŠน์ง•์œผ๋กœ๋Š” ๊ณผ๋ฐ˜์ˆ˜๊ฐ€ ๋ณด์žฅ์ด ๋˜์–ด์•ผ ํ•˜๋ฉฐ ์šฐ๋ฆฌ๊ฐ€ ์•Œ์•„๋‚ผ ์ˆ˜ ์ž‡๋Š” ๊ฒƒ์€ ๊ณผ๋ฐ˜์ˆ˜ ์ด์ƒ์˜ ์ˆซ์ž๋ฅผ ์ฐพ์•„๋‚ด๋Š” ๊ฒƒ์ด๋‹ค.

์ด๋ฅผ ๊ฐ€์žฅ ์ž˜ ๋‚˜ํƒ€๋‚ด๋Š” ๊ทธ๋ฆผ์ด ์žˆ๋‹ค.

์ฆ๋ช…

์ฝ”๋“œ๋กœ ๋ณด์ž.

count = 0
        ret = -1

        for num in nums:
            if count == 0: ret = num
            if ret == num: count += 1
            else: count -= 1
        return ret
  • Time Complexity : O(n)
  • Space Complexity : O(1)

๊ฐ€์žฅ ๋น ๋ฅด๋ฉฐ ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์ด ํ•„์š”์—†๋Š” ํ’€์ด์ด๋‹ค. ๋ ˆ๋ฒจ์€ easy์ด๋‚˜ ๋งŽ์€ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ธ ๊ฑฐ ๊ฐ™๋‹ค.