Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 229 · Moore Voting

Majority Element II

LeetCode 229 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Count and keep values with count > n // 3.

ಮಧ್ಯಮArrayHash TableSortingCountingBoyer–Moore Majority Vote Algorithm
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Majority Element II (LeetCode 229) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Moore Voting ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.

Approach

  1. 1

    Count frequencies.

  2. 2

    Keep each value whose count exceeds n // 3.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Counter filterPythonO(n) time · O(n) space
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        n = len(nums)
        mpp = Counter(nums)
        res = []
        for key,val in mpp.items():
            if val>(n//3):
                res.append(key)
        return res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Majority Element II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Majority Element II ಹಿಂದಿನ intuition ಏನು?

Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.

Majority Element II (LeetCode 229) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Count frequencies. 2. Keep each value whose count exceeds n // 3.

Majority Element II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(n). (Accepted approach: Counter filter.)

Majority Element II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Extended Boyer–Moore (two candidates) does it in O(1) space.