lintcode_46.主元素
阿新 • • 發佈:2017-12-18
can bsp body 整型 返回 sort self class lis
給定一個整型數組,找出主元素,它在數組中的出現次數嚴格大於數組元素個數的二分之一。
註意事項
You may assume that the array is non-empty and the majority number always exist in the array.
樣例
給出數組[1,1,1,1,2,2,2],返回 1
思路:
1.計數,找數量最多的元素
2.主元素個數大於數量的二分之一,所以排序後的中間元素一定為主元素
class Solution: """ @param: nums: a list of integers @return: find a majority number""" def majorityNumber(self, nums): # write your code here nums.sort() return nums[len(nums)/2]
九章:
class Solution: def majorityNumber(self, nums): candidate = None count = 0 for num in nums: if count == 0: candidate= num count += 1 elif candidate == num: count += 1 else: count -= 1 return candidate
lintcode_46.主元素