LeetCode #1150. Check If a Number Is Majority Element in a Sorted Array

题目

1150. Check If a Number Is Majority Element in a Sorted Array


解题方法

首先用二分查找找到target在数组中的位置,然后从这个位置开始向左右延申找到端点,计算元素个数,再和 len(nums) // 2 对比即可。
时间复杂度:O(n)
空间复杂度:O(1)


代码

class Solution:
    def binarySearch(self, nums, left, right, target):
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return -1
    
    def isMajorityElement(self, nums: List[int], target: int) -> bool:
        left = right = targetindex = self.binarySearch(nums, 0, len(nums)-1, target)
        
        while left > -1 and nums[left] == target: left -= 1
        
        while right < len(nums) and nums[right] == target: right += 1
        
        return right - left - 1 > len(nums) // 2
posted @ 2020-12-01 14:02  老鼠司令  阅读(45)  评论(0编辑  收藏  举报