数组中出现次数超过一半的数字
2021-01-06 本文已影响0人
九日火
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
class Solution:
def MoreThanHalf(self, numbers):
length = len(numbers)
if numbers == None or length <= 0:
return 0
result = numbers[0]
times = 1
for i in range(1, length):
if times == 0:
result = numbers[i]
times = 1
elif numbers[i] == result:
times += 1
else:
times -= 1
if not self.CheckMoreThanHalf(numbers, length, result):
result = 0
return result
def CheckMoreThanHalf(self, numbers, length, num):
times = 0
for i in range(length):
if numbers[i] == result:
times += 1
if times * 2 <= length:
return False
return True
package main
import "errors"
func MoreThanHalf(nums []int) (int, error) {
if len(nums) == 0 {return -1, errors.New("array is empty")}
count := 1
value := nums[0]
for i := 1; i<len(nums); i++ {
if nums[i] == value {
count += 1
} else if count == 0 {
value = num[i]
count = 1
} else {
count -= 1
}
}
if not CheckMoreThanHalf(nums, value) {return -1, errors.New("num's length lower than half of array")}
}
func CheckMoreThanHalf(nums []int, num int) bool {
count = 0
for i := 0; i<len(nums); i++ {
if num[i] == num {
count += 1
}
}
if count * 2 <= len(nums) {return false}
return true
}