1 条题解

  • 0
    @ 2025-2-14 19:57:28

    Python :

    # coding=utf-8
    def find_majority_element(nums):
        candidate = None
        count = 0
        
        # 第一阶段:找出候选元素
        for num in nums:
            if count == 0:
                candidate = num
            count += (1 if num == candidate else -1)
        
        # 第二阶段:验证候选元素是否为多数元素
        count = 0
        for num in nums:
            if num == candidate:
                count += 1
        
        if count > len(nums) // 2:
            return candidate
        else:
            return "no"
    
    # 读取输入
    n = int(input().strip())
    nums = list(map(int, input().strip().split()))
    
    # 输出结果
    print(find_majority_element(nums))
    
    • 1

    信息

    ID
    187
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者