当前位置:网站首页>Interview question 17.10 Main elements

Interview question 17.10 Main elements

2022-04-23 16:03:00 Zhang Joshua

Interview questions 17.10. Main elements

Ideas :

  • 1. The difficulty of this problem is that the time complexity is O(N), The space complexity is O(1) The requirements of . Using Moore voting
  • 2. Moore voting :
     Insert picture description here
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = 0
        ans = 0
        for num in nums:
            if count==0:
                ans = num
            if ans == num:
                count += 1
            if ans != num:
                count -= 1
        if nums.count(ans) > len(nums)//2:
            return ans
        else:
            return -1

版权声明
本文为[Zhang Joshua]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231558306163.html