题解 | #剪绳子#
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int ans=numbers[0];
int count=1;
for(int i=1;i<numbers.size();++i)
{
if(count>0)
{
if(ans==numbers[i])
count++;
else
count--;
}
else
{
ans=numbers[i];
count++;
}
}
return ans;
}
};
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int ans=numbers[0];
int count=1;
for(int i=1;i<numbers.size();++i)
{
if(count>0)
{
if(ans==numbers[i])
count++;
else
count--;
}
else
{
ans=numbers[i];
count++;
}
}
return ans;
}
};