数组中有一个数字出现的次数超过了数组长度的一半,找出这个数,如果不存在返回0。
由于这个数是超过数组数字总量的一半,则用以下思路处理。
定义一个整数a用来存储数组的最多的那个数字,定义另外一个整数b用来存储数字的次数。
遍历整个数组,如果b为0,另a为当前数组的数字;
如果当前的数字等于a,令b+1;
如果当前的数字不等于a,且b不为0,则令b-1;
最后a得到的数字如果满足出现的次数大于数组总量的一半,则返回a的值。
python代码:
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
length = len(numbers)
# write code here
if not numbers:
return 0
number = 1
moreOfHalf = numbers[0]
for i in range(1,length):
if number == 0:
number = 1
moreOfHalf = numbers[i]
elif numbers[i] == moreOfHalf:
number += 1
else:
number -= 1
if self.checkIsHalf(numbers,moreOfHalf,length):
return moreOfHalf
else:
return 0
def checkIsHalf(self,numbers,number,length):
times = 0
for i in range(0,length):
if numbers[i] == number:
times += 1
if times*2<=length:
return False
else:
return True
C++代码:
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
if(numbers.empty()){
return 0;
}
int length = numbers.size();
int number = 1;
int mostOfList = numbers[0];
for(int i=1;i<length;i++){
if(number == 0){
mostOfList = numbers[i];
number = 1;
}
else if(numbers[i] == mostOfList){
number++;
}
else{
number--;
}
}
if(checkOfIsHalf(numbers,mostOfList,length)){
return mostOfList;
}
else{
return 0;
}
}
bool checkOfIsHalf(vector<int> numbers,int number,int length){
int times = 0;
for(int i=0;i<length;i++){
if(numbers[i] == number){
times++;
}
}
if(times*2<=length){
return false;
}
else{
return true;
}
}
};